Skip to content

Instantly share code, notes, and snippets.

@hardiksondagar
Created February 26, 2019 11:48
Show Gist options
  • Save hardiksondagar/183cb4503ae26fa8fec5fd72bdcc95d0 to your computer and use it in GitHub Desktop.
Save hardiksondagar/183cb4503ae26fa8fec5fd72bdcc95d0 to your computer and use it in GitHub Desktop.
Python - Logging configuration
---
version: 1
disable_existing_loggers: False
formatters:
simple:
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
handlers:
console:
class: logging.StreamHandler
level: DEBUG
formatter: simple
stream: ext://sys.stdout
info_file_handler:
class: logging.handlers.RotatingFileHandler
level: INFO
formatter: simple
filename: /var/log/your-app/info.log
maxBytes: 52428800 # 50MB
backupCount: 10
encoding: utf8
error_file_handler:
class: logging.handlers.RotatingFileHandler
level: ERROR
formatter: simple
filename: /var/log/your-app/error.log
maxBytes: 52428800 # 50MB
backupCount: 10
encoding: utf8
loggers:
interpolation:
level: DEBUG
handlers: [console, info_file_handler, error_file_handler]
propagate: no
root:
level: DEBUG
handlers: [console, info_file_handler, error_file_handler]
...
import logging
import logging.config
import os
import yaml
def setup_logging(
default_path='logging.yaml', default_level=logging.INFO, env_key='LOG_CFG'
):
"""
Setup logging configuration
"""
path = dir_path + "/" + default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, 'rt') as f:
config = yaml.safe_load(f.read())
logging.config.dictConfig(config)
else:
logging.basicConfig(level=default_level)
setup_logging()
logger = logging.getLogger('your-logger-name')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment