Logger
config.logging.py
import logging.config
import os
from pathlib import Path
import yaml
def configure_logging(log_config_path, log_directory):
with open(log_config_path, 'r') as f:
= yaml.safe_load(f)
config 'handlers']['file']['filename'] = str(log_directory / config['handlers']['file']['filename'])
config[
logging.config.dictConfig(config)
= Path(__file__).resolve().parent.parent
project_root = project_root / 'logs'
logs_directory =True)
logs_directory.mkdir(exist_ok
= project_root / 'config' / 'logging.yaml'
logging_config_path
configure_logging(logging_config_path, logs_directory)
= logging.getLogger("package_name")
logger
"Logging started") logger.info(
config.logging.yml
version: 1
formatters:
simple:
format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
console:
class: logging.StreamHandler
level: INFO
formatter: simple
file:
class: logging.FileHandler
level: INFO
formater: simple
filename: package_name.log
loggers:
root:
level: INFO
handlers: [console, file]
package_name:
level: INFO
handlers: [console, file]
root:
level: INFO
handlers: [console, file]
We can then use it by:
import logging
= logging.getLogger(__name__) logger
This will place the package_name.log
logfile under projectroot/logs
directory.