Skip to content

Instantly share code, notes, and snippets.

@sam2332
Created February 22, 2022 17:23
Show Gist options
  • Save sam2332/d5957c3fb753cec05d8a3058a7e6e0ba to your computer and use it in GitHub Desktop.
Save sam2332/d5957c3fb753cec05d8a3058a7e6e0ba to your computer and use it in GitHub Desktop.
Easy Python Logging setup
##Magic Logging Bootstrap
import logging
import sys
logging.basicConfig(
filename='randomWp.log',
level=logging.INFO,
format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
exlogger = logging.getLogger("Exception")
def handle_exception(exc_type, exc_value, exc_traceback):
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_traceback)
return
exlogger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
sys.excepthook = handle_exception
class StreamToLogger(object):
"""
Fake file-like stream object that redirects writes to a logger instance.
"""
def __init__(self, logger, level):
self.logger = logger
self.level = level
self.linebuf = ''
def write(self, buf):
for line in buf.rstrip().splitlines():
self.logger.log(self.level, line.rstrip())
def flush(self):
pass
log = logging.getLogger('Stdout')
sys.stdout = StreamToLogger(log,logging.INFO)
log = logging.getLogger('Stderr')
sys.stderr = StreamToLogger(log,logging.ERROR)
##Finished Magic Logging Bootstrap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment