Python Logging Module Implementation
Logging Fundamentals
Logging provides a mechanism to track software runtime events. Developers instrument their code with logging calls to capture system activities. Each event consists of a descriptive message that may include variable data and is assigned a severity level.
Log Severity Levels
| Level | Usage |
|---|---|
| DEBUG | Detailed diagnostic information for troubleshooting |
| INFO | Confirmation of expected operation |
| WARNING | Unexpected but non-critical conditions |
| ERROR | Functional impairment in specific features |
| CRITICAL | System failure preventing continued operation |
Log levels follow an increasing severity hierarchy where higher levels represent more critical events with less verbose output.
Basic Logging Implementation
import logging
logging.debug("Detailed trace information")
logging.info("Operation confirmation")
logging.warning("Non-critical issue detected")
logging.error("Functional failure occurred")
logging.critical("System failure condition")
"""
Output:
WARNING:root:Non-critical issue detected
ERROR:root:Functional failure occurred
CRITICAL:root:System failure condition
"""
Log Formatting Attributes
| Attribute | Format | Description |
|---|---|---|
| timestamp | %(asctime)s | Event occurrence time |
| level | %(levelname)s | Severity designation |
| source | %(filename)s | Origin script name |
| position | %(lineno)d | Code line reference |
| message | %(message)s | Descriptive content |
Structured Logging Implementation
import logging
# Initialize logger
app_logger = logging.getLogger('application.core')
app_logger.setLevel(logging.DEBUG)
# Configure output handlers
console_output = logging.StreamHandler()
file_output = logging.FileHandler('app_activity.log', mode='w')
# Define message format
log_format = logging.Formatter('%(asctime)s|%(levelname)8s|%(filename)s[:%(lineno)d]|%(message)s')
# Apply formatting
console_output.setFormatter(log_format)
file_output.setFormatter(log_format)
# Register handlers
app_logger.addHandler(console_output)
app_logger.addHandler(file_output)
# Generate log events
user = 'admin'; id = 42
app_logger.debug('User %s initiated session, ID %d', user, id)
app_logger.info('Configuration loaded for %s', user)
app_logger.warning('Resource threshold exceeded: %d%%', 85)
Configuration File Implementation
# app_log.conf
[loggers]
keys=root,app
[handlers]
keys=file_handler,console_handler
[formatters]
keys=standard_format
[logger_root]
level=INFO
handlers=console_handler
[logger_app]
level=DEBUG
handlers=file_handler,console_handler
qualname=app
propagate=0
[handler_console_handler]
class=StreamHandler
args=(sys.stdout,)
level=INFO
formatter=standard_format
[handler_file_handler]
class=handlers.TimedRotatingFileHandler
args=('app.log','midnight',1,0)
level=DEBUG
formatter=standard_format
[formatter_standard_format]
format=%(asctime)s|%(levelname)8s|%(filename)s[:%(lineno)d]|%(message)s
datefmt=%Y-%m-%d %H:%M:%S
Configuration Loading
import logging
import logging.config
logging.config.fileConfig('app_log.conf')
system_log = logging.getLogger()
app_log = logging.getLogger('app')
app_log.debug('Debugging component initialization')
app_log.info('Application started')
try:
result = 10 / 0
except Exception as e:
app_log.exception('Calculation error: %s', e)