Skip to content

Instantly share code, notes, and snippets.

@dalegaspi
Created August 1, 2019 02:55
Show Gist options
  • Save dalegaspi/557a899c23e3f7edc9bc90aa536c3dfa to your computer and use it in GitHub Desktop.
Save dalegaspi/557a899c23e3f7edc9bc90aa536c3dfa to your computer and use it in GitHub Desktop.
Python Logging with YAML configuration
import logging
import logging.config
import yaml
from pathlib import Path
# https://stackoverflow.com/a/52266636/918858
here = Path(__file__).parent
LOG_CFG = here/'logging.yaml'
def init_default_local_logging():
with open(LOG_CFG, 'rt') as f:
config = yaml.safe_load(f.read())
logging.config.dictConfig(config)
# in use
init_default_local_logging()
logger = logging.getLogger(__name__)
# this should not disable any logging configuration from things like imported libraries
logger.info("hello")
---
version: 1
# this disable_existing_loggers set to False is critical, otherwise if you load this config, it disables existing loggers
disable_existing_loggers: False
formatters:
simple:
format: '%(asctime)s %(levelname)s %(name)s - %(message)s'
datefmt: '%Y-%m-%d %H:%M:%S'
handlers:
console:
class: logging.StreamHandler
formatter: simple
level: DEBUG
stream: ext://sys.stdout
file:
class: logging.handlers.RotatingFileHandler
formatter: simple
level: DEBUG
filename: my_log.log
maxBytes: 1048576
backupCount: 3
root:
level: DEBUG
handlers: [console, file]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment