Last active
April 13, 2020 19:49
-
-
Save ygivenx/306f2e4e1506f302504fb67abef50652 to your computer and use it in GitHub Desktop.
Inject extra keys to log messages in python
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 | |
import os | |
LOG_FORMAT = '%(asctime)s %(name)s %(levelname)s %(funcName)s %(lineno)s ClaimID: %(claim_id)s: %(message)s' | |
class AppLogger(logging.Logger): | |
# Override all levels similarly - only info overriden here | |
def info(self, msg, *args, **kwargs): | |
return super(AppLogger, self).info(msg, extra={"claim_id": os.getenv("claim_id", "")}) | |
def get_logger(name): | |
""" This function sets log level and log format and then returns the instance of logger""" | |
logging.setLoggerClass(AppLogger) | |
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT) | |
logger = logging.getLogger(name) | |
logger.setLevel(logging.INFO) | |
return logger | |
LOGGER = get_logger(__name__) | |
LOGGER.info("Hey") | |
os.environ["claim_id"] = "12334" | |
LOGGER.info("Hey") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment