Skip to content

Instantly share code, notes, and snippets.

@DeeprajPandey
Created May 4, 2023 14:31
Show Gist options
  • Save DeeprajPandey/c636b7d8679d6fccbc7d1ccfc0c74032 to your computer and use it in GitHub Desktop.
Save DeeprajPandey/c636b7d8679d6fccbc7d1ccfc0c74032 to your computer and use it in GitHub Desktop.
Python Logger Config
import logging
import logging.config
import os
LOGGING_CONFIG = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"standardFormatter": {
"format": "%(asctime)s %(levelname)s %(name)s: %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S",
},
"securityFormatter": {
"format": "%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S",
},
"verboseFormatter": {
"format": "%(asctime)s %(levelname)s %(module)s %(process)d %(thread)d %(filename)s:%(lineno)d %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S",
},
},
"handlers": {
"consoleHandler": {
"class": "logging.StreamHandler",
"level": "INFO",
"formatter": "standardFormatter",
"stream": "ext://sys.stdout",
},
"fileHandler": {
"class": "logging.handlers.RotatingFileHandler",
"level": "DEBUG",
"formatter": "verboseFormatter",
"filename": os.path.join(
os.getcwd(), "logs", "all.log"
),
"maxBytes": 1024 * 1024 * 5, # 5 MB
"backupCount": 5,
},
},
"loggers": {
"root": {"level": "WARNING", "handlers": ["consoleHandler", "fileHandler"]},
"security": {
"level": "INFO",
"handlers": ["fileHandler"],
"qualname": "security",
"propagate": False,
},
"debug": {"level": "DEBUG", "handlers": ["consoleHandler"], "propagate": False},
},
}
# Load the logging configuration
try:
logging.config.dictConfig(LOGGING_CONFIG)
except ValueError as e:
raise SystemExit(f"Error in logging configuration: {e}")
RootLogger = logging.getLogger("root")
SecurityLogger = logging.getLogger("security")
DebugLogger = logging.getLogger("debug")
from logging_config import DebugLogger, SecurityLogger
# First in root; mkdir logs/
# Get the loggers
# Default logger: info and above to a rotating file; not propagated to root logger
logger = SecurityLogger
# Debug logger: debug and above to only the console; not propagated to root logger
debug_logger = DebugLogger
# Please add strings and test
logger.debug()
logger.info()
logger.warn()
logger.error()
logger.exception()
debug_logger.debug()
debug_logger.info()
debug_logger.warn()
debug_logger.error()
debug_logger.exception()
logging==0.4.9.6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment