Python - Logging
Logging:
Good info on logging: https://realpython.com/python-logging/. It has lot of good scenarios with examples explained well.
Simple Example from above reference:
import logging
# Simplest usecase:
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')
Better formatting and configs:
- Configure to log in specific file, with specific format
- Config can be saved in YAML syntax and read also. More info: https://realpython.com/python-logging/#other-configuration-methods
logging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')
logging.warning('This will get logged to a file')
Get logger instance for specific package.module
logger = logging.getLogger("package.module")
logger.setLevel(logging.ERROR)
Add filter to logger:
- This will be helpfull to see logs for specific package
- or logs message of specific pattern
logger = logging.getLogger(__name__)
logger.addFilter(lambda x: x.name.startswith("package_name") && x.levelname == "INFO")