Junior
How to add logging to any Python script?
sobes.tech AI
Answer from AI
For basic logging:
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def my_function():
logging.info("Start of my_function")
# Your code
logging.debug("Debugging intermediate information")
try:
result = 1 / 0
except ZeroDivisionError:
logging.error("Division by zero error")
logging.info("End of my_function")
my_function()
For more flexible configuration, you can use a configuration file or dictionary:
import logging
import logging.config
# Example configuration in a dictionary
log_config = {
'version': 1,
'formatters': {
'simpleFormatter': {
'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
},
},
'handlers': {
'consoleHandler': {
'class': 'logging.StreamHandler',
'formatter': 'simpleFormatter',
'level': 'INFO'
},
'fileHandler': {
'class': 'logging.FileHandler',
'formatter': 'simpleFormatter',
'level': 'DEBUG',
'filename': 'app.log'
}
},
'loggers': {
'myApp': {
'handlers': ['consoleHandler', 'fileHandler'],
'level': 'DEBUG'
'propagate': False
}
},
'root': {
'handlers': ['consoleHandler'],
'level': 'INFO'
}
}
logging.config.dictConfig(log_config)
logger = logging.getLogger('myApp')
def another_function():
logger.info("Executing another_function")
logger.debug("Execution details")
another_function()
Key elements:
logging.basicConfig(): The simplest way to configure the root logger.logging.getLogger(name): Gets an instance of a logger. Using names allows creating a hierarchy of loggers for modules or applications.- Logging levels:
DEBUG: Detailed information useful for debugging.INFO: General information about execution progress.WARNING: Warning about potential issues.ERROR: An error that does not stop program execution.CRITICAL: Critical error after which the program may terminate.
- Handlers: Define where to send log messages (console, file, network, etc.).
- Formatters: Define the output format of log messages.