Skip to content

Instantly share code, notes, and snippets.

@nikitagashkov
Created February 19, 2019 12:13
Show Gist options
  • Save nikitagashkov/8c97f5ea4080ea437b35843dbf0e6c37 to your computer and use it in GitHub Desktop.
Save nikitagashkov/8c97f5ea4080ea437b35843dbf0e6c37 to your computer and use it in GitHub Desktop.
Logging configuration with console and file handlers
import logging
import logging.config
import settings
def setup_logging():
logging.config.dictConfig(settings.LOGGING_CONFIG)
log = logging.getLogger("sys.excepthook")
def excepthook(exc_type, exc_value, exc_traceback):
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_traceback)
return
log.critical("Uncaught exception.", exc_info=(exc_type, exc_value, exc_traceback))
sys.excepthook = excepthook
def main():
setup_logging()
log = logging.getLogger(__name__)
log.info("Hello, world!")
if __name__ == "__main__":
main()
import os
LOGGING_CONFIG = {
"disable_existing_loggers": False,
"version": 1,
"formatters": {
"short": {
"format": "%(asctime)s %(levelname)s %(name)s: %(message)s"
},
},
"handlers": {
"console": {
"level": "INFO",
"formatter": "short",
"class": "logging.StreamHandler",
},
"file-debug": {
"level": "DEBUG",
"formatter": "short",
"class": "logging.handlers.RotatingFileHandler",
"filename": os.path.join(BASE_DIR, "logs", "debug.log"),
"maxBytes": 5*1024*1024,
"backupCount": 10,
"mode": "a",
"encoding": "utf-8",
},
"file-error": {
"level": "ERROR",
"formatter": "short",
"class": "logging.handlers.RotatingFileHandler",
"filename": os.path.join(BASE_DIR, "logs", "error.log"),
"maxBytes": 5*1024*1024,
"backupCount": 10,
"mode": "a",
"encoding": "utf-8",
},
},
"loggers": {
"": {
"handlers": ["console", "file-debug", "file-error"],
"level": "DEBUG",
},
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment