Created
July 7, 2017 21:51
-
-
Save mmparker/3bd6cb5a4e791dc165d9421b81d98b78 to your computer and use it in GitHub Desktop.
Trying to understand logging in Python with structlog...
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
# Two main things I can't figure out: | |
# 1. How do I get the name of each function to prefix its log entry? | |
# e.g., INFO:testmodule:outsideFun:{msg} instead of just INFO:testmodule:{msg} | |
# 2. How do I get bound values to persist through subsequent functions? | |
# e.g., user:matt.parker and outsideArg:foo should appear in both | |
# outsideFun and insideFun log messages | |
import logging | |
import structlog | |
import testmodule | |
# Set up the log | |
logging.basicConfig(level = logging.DEBUG) | |
structlog.configure( | |
processors = [structlog.stdlib.filter_by_level, | |
structlog.processors.format_exc_info, | |
structlog.processors.TimeStamper(fmt = 'iso'), | |
structlog.processors.JSONRenderer()], | |
context_class = dict, | |
logger_factory = structlog.stdlib.LoggerFactory(), | |
wrapper_class = structlog.stdlib.BoundLogger, | |
cache_logger_on_first_use = True | |
) | |
logger = structlog.get_logger() | |
# Bind a key-value that should appear in all output | |
logger = logger.bind(user = "matt.parker") | |
# Run the function | |
testmodule.outsideFun() |
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 structlog | |
module_logger = structlog.get_logger() | |
def insideFun(insideArg = "bar"): | |
logger = structlog.get_logger() | |
logger = logger.bind(insideArg = insideArg) | |
logger.info("Inside function has begun.") | |
print insideArg | |
logger.info("Inside function complete.") | |
def outsideFun(outsideArg = "foo"): | |
logger = structlog.get_logger() | |
logger = logger.bind(outsideArg = outsideArg) | |
logger.info("Starting the outside function...") | |
insideFun() | |
logger.info("Outside function complete.") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment