Created
July 3, 2022 21:10
-
-
Save hodbn/56d56b2529a5a3c54cfc6b4d999f9d7c to your computer and use it in GitHub Desktop.
Structlog integration with urllib3
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
def setup_structlog(level: int = logging.DEBUG) -> None: | |
timestamper = structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M:%S") | |
shared_processors = [ | |
structlog.stdlib.add_log_level, | |
timestamper, | |
] | |
structlog.configure( | |
processors=shared_processors | |
+ [ | |
structlog.stdlib.ProcessorFormatter.wrap_for_formatter, | |
], | |
logger_factory=structlog.stdlib.LoggerFactory(), | |
cache_logger_on_first_use=True, | |
) | |
formatter = structlog.stdlib.ProcessorFormatter( | |
# These run ONLY on `logging` entries that do NOT originate within | |
# structlog. | |
foreign_pre_chain=shared_processors, | |
# These run on ALL entries after the pre_chain is done. | |
processors=[ | |
# Remove _record & _from_structlog. | |
structlog.stdlib.ProcessorFormatter.remove_processors_meta, | |
structlog.dev.ConsoleRenderer(), | |
], | |
) | |
handler = logging.StreamHandler() | |
# Use OUR `ProcessorFormatter` to format all `logging` entries. | |
handler.setFormatter(formatter) | |
root_logger = logging.getLogger() | |
root_logger.addHandler(handler) | |
root_logger.setLevel(level) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment