Created
August 1, 2019 02:55
-
-
Save dalegaspi/557a899c23e3f7edc9bc90aa536c3dfa to your computer and use it in GitHub Desktop.
Python Logging with YAML configuration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
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