Skip to content

Instantly share code, notes, and snippets.

@yeger00
Last active December 19, 2021 15:05
Show Gist options
  • Save yeger00/c97cc1d82d521fb725afaabca3b2ec0b to your computer and use it in GitHub Desktop.
Save yeger00/c97cc1d82d521fb725afaabca3b2ec0b to your computer and use it in GitHub Desktop.
import logging
class SafeLog:
def __init__(self, log: logging.Logger):
self.log = log
self.safe = False
def __enter__(self):
self.safe = True
return self
def __getattr__(self, key):
if not self.safe:
self.log.warn("Using unsafe log")
return getattr(self.log, key)
def __exit__(self, type, value, traceback):
self.safe = False
if type or value or traceback:
# Log the exception and prevent from propagate
self.log.exception("Error writing to log")
return True
return False
# Example usage:
log = logging.getLogger()
safelog = SafeLog(log)
with safelog: safelog.info(f"this will not throw {di['key']}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment