Last active
December 19, 2021 15:05
-
-
Save yeger00/c97cc1d82d521fb725afaabca3b2ec0b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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