Python Logging Implementation
Page Info
Content
Python Logging Implementation
In Python, the built-in logging
module allows you to track events that occur during program execution. Logging is more flexible than print()
statements because it provides log levels, formatting, and the ability to write logs to files.
Basic Logging Example
import logging
# Configure basic logging
logging.basicConfig(level=logging.INFO)
# Example log messages
logging.debug("This is a debug message")
logging.info("This is an info message")
logging.warning("This is a warning message")
logging.error("This is an error message")
logging.critical("This is a critical message")
Explanation:
logging.basicConfig(level=logging.INFO)
: Sets the logging level (INFO and above are displayed).- Different log levels:
DEBUG
,INFO
,WARNING
,ERROR
,CRITICAL
.
Logging to a File
import logging
# Configure logging to write to a file
logging.basicConfig(
filename='app.log',
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logging.info("Program started")
logging.warning("This is a warning")
logging.error("An error occurred")
Explanation:
filename='app.log'
: Logs are saved toapp.log
instead of the console.format='%(asctime)s - %(levelname)s - %(message)s'
: Custom format including timestamp, log level, and message.
Advanced Logging with Multiple Levels
import logging
# Create a logger object
logger = logging.getLogger("my_logger")
logger.setLevel(logging.DEBUG)
# Create console handler
ch = logging.StreamHandler()
ch.setLevel(logging.WARNING)
# Create formatter and add to handler
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
# Add handler to logger
logger.addHandler(ch)
# Example messages
logger.debug("Debug message") # Won't appear in console
logger.info("Info message") # Won't appear in console
logger.warning("Warning message") # Will appear
logger.error("Error message") # Will appear
Key Points
- Flexible log levels: Control the verbosity of your logs with DEBUG, INFO, WARNING, ERROR, and CRITICAL.
- Logging output: Logs can be written to console, files, or both.
- Formatting: Include timestamps, logger names, and log levels for better traceability.
- Better than print(): Logging is non-intrusive and can be easily disabled or redirected.
SEO Keywords
Python logging example, Python log to file, Python logger, Python logging levels, Python debug info warning error, Python logging configuration
Use Python's logging module to track program execution, handle debugging information, and save logs for later analysis efficiently and flexibly.
Good0 Bad0
댓글목록
등록된 댓글이 없습니다.