Skip to content

Instantly share code, notes, and snippets.

@mmparker
Created July 7, 2017 21:51
Show Gist options
  • Save mmparker/3bd6cb5a4e791dc165d9421b81d98b78 to your computer and use it in GitHub Desktop.
Save mmparker/3bd6cb5a4e791dc165d9421b81d98b78 to your computer and use it in GitHub Desktop.
Trying to understand logging in Python with structlog...
# 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()
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