### Install Structlog Source: https://github.com/hynek/structlog/blob/main/docs/getting-started.md Install structlog using pip. For pretty exceptions, also install Rich. On Windows, install Colorama for colorful output. ```console python -m pip install structlog ``` -------------------------------- ### Structlog Logger Configuration Example Source: https://github.com/hynek/structlog/blob/main/docs/processors.md Illustrates how to configure structlog with a list of processors and bind initial context to a logger. ```python structlog.configure(processors=[f1, f2, f3]) log = structlog.get_logger().bind(x=42) ``` -------------------------------- ### Production-Ready Structlog Configuration with orjson Source: https://github.com/hynek/structlog/blob/main/docs/performance.md An example of a high-performance structlog configuration using `orjson` for JSON rendering, `BytesLoggerFactory`, and efficient level filtering. This setup minimizes overhead for production logging. ```python import logging import orjson import structlog structlog.configure( cache_logger_on_first_use=True, wrapper_class=structlog.make_filtering_bound_logger(logging.INFO), processors=[ structlog.contextvars.merge_contextvars, structlog.processors.add_log_level, structlog.processors.format_exc_info, structlog.processors.TimeStamper(fmt="iso", utc=True), structlog.processors.JSONRenderer(serializer=orjson.dumps), ], logger_factory=structlog.BytesLoggerFactory(), ) ``` -------------------------------- ### Your First Structlog Log Entry Source: https://github.com/hynek/structlog/blob/main/docs/getting-started.md A simple example of logging an info message with structlog. It demonstrates basic interpolation and keyword arguments. ```python import structlog log = structlog.get_logger() log.info("hello, %s!", "world", key="value!", more_than_strings=[1, 2, 3]) # doctest: +SKIP ``` -------------------------------- ### Structlog Processor Call Chain Example Source: https://github.com/hynek/structlog/blob/main/docs/processors.md Demonstrates the nested call structure of processors when a log event is processed. ```python wrapped_logger.info( f3(wrapped_logger, "info", f2(wrapped_logger, "info", f1(wrapped_logger, "info", {"event": "some_event", "x": 42, "y": 23}) ) ) ) ``` -------------------------------- ### Logging Output Examples with Structlog and Standard Logging Source: https://github.com/hynek/structlog/blob/main/docs/standard-library.md These examples showcase the output generated by both standard Python logging and structlog when integrated. The first example logs a message using the standard `logging` module, showing the timestamp, log level, message, process name, and thread name. The second example logs a message using structlog, including an additional key-value argument, demonstrating how structlog appends structured data to the log output. The third example reads the content of a log file, illustrating the final formatted output for both types of log entries. ```python >>> logging.getLogger().warning("bar") 2021-11-15 13:26:52 [warning ] bar process_name=MainProcess thread_name=MainThread ``` ```python >>> structlog.get_logger("structlog").warning("foo", x=42) 2021-11-15 13:26:52 [warning ] foo process_name=MainProcess thread_name=MainThread x=42 ``` ```python >>> pathlib.Path("test.log").read_text() 2021-11-15 13:26:52 [warning ] bar 2021-11-15 13:26:52 [warning ] foo x=42 ``` -------------------------------- ### Basic structlog Logger Initialization Source: https://github.com/hynek/structlog/blob/main/docs/configuration.md Demonstrates the minimal boilerplate required to get a structlog logger using `structlog.get_logger()`. This function relies on configuration set by `structlog.configure()`. ```python import structlog logger = structlog.get_logger() ``` -------------------------------- ### Standard Logging Example (Non-JSON) Source: https://github.com/hynek/structlog/blob/main/docs/standard-library.md Demonstrates logging a warning message using the standard `logging` module after it has been configured to output plain text. This shows the difference in output compared to structlog's JSON formatting. ```python >>> logging.getLogger("test").warning("hello") ``` -------------------------------- ### Basic Structlog and Standard Logging Output Comparison Source: https://github.com/hynek/structlog/blob/main/docs/standard-library.md Compares the output of standard library logging and structlog logging when both are configured. This example highlights the differences in how messages are presented before advanced formatting is applied. ```python >>> import logging >>> import structlog >>> logging.getLogger("stdlog").info("woo") woo _from_structlog=False _record= >>> structlog.get_logger("structlog").info("amazing", events="oh yes") amazing _from_structlog=True _record= events=oh yes ``` -------------------------------- ### Configure structlog with KeyValueRenderer Source: https://github.com/hynek/structlog/blob/main/docs/thread-local.md This snippet demonstrates how to configure structlog globally to use the KeyValueRenderer processor. This setup is typically used for testing purposes to ensure a consistent logging format. ```python import structlog structlog.configure( processors=[structlog.processors.KeyValueRenderer()], ) ``` -------------------------------- ### Structlog JSON Log Example Source: https://github.com/hynek/structlog/blob/main/docs/standard-library.md Demonstrates logging a warning message using structlog after configuration. The output is a JSON string containing the event message, logger name, log level, and timestamp. ```python >>> structlog.get_logger("test").warning("hello") ``` -------------------------------- ### Custom Bound Logger Example Source: https://github.com/hynek/structlog/blob/main/docs/recipes.md Defines and uses a custom bound logger 'SemanticLogger' that adds a 'status' attribute to 'info' events if not already present, and uses 'info' for 'user_error' events. This example demonstrates subclassing BoundLoggerBase and using wrap_logger. ```python from structlog import BoundLoggerBase, PrintLogger, wrap_logger class SemanticLogger(BoundLoggerBase): def info(self, event, **kw): if not "status" in kw: return self._proxy_to_logger("info", event, status="ok", **kw) else: return self._proxy_to_logger("info", event, **kw) def user_error(self, event, **kw): self.info(event, status="user_error", **kw) log = wrap_logger(PrintLogger(), wrapper_class=SemanticLogger) log = log.bind(user="fprefect") log.user_error("user.forgot_towel") ``` -------------------------------- ### Configure and Use Context Variables with structlog Source: https://github.com/hynek/structlog/blob/main/docs/contextvars.md Demonstrates how to configure structlog to use context variables, bind and unbind variables, and log messages. This example shows the general flow for integrating contextvars with structlog, including clearing and temporarily overriding context variables. ```python from structlog.contextvars import ( bind_contextvars, bound_contextvars, clear_contextvars, merge_contextvars, unbind_contextvars, ) from structlog import configure configure( processors=[ merge_contextvars, structlog.processors.KeyValueRenderer(key_order=["event", "a"]), ] ) log = structlog.get_logger() # At the top of your request handler (or, ideally, some general # middleware), clear the contextvars-local context and bind some common # values: clear_contextvars() bind_contextvars(a=1, b=2) # Then use loggers as per normal # (perhaps by using structlog.get_logger() to create them). log.info("hello") # Use unbind_contextvars to remove a variable from the context. unbind_contextvars("b") log.info("world") # You can also bind key-value pairs temporarily. with bound_contextvars(b=2): log.info("hi") # Now it's gone again. log.info("hi") # And when we clear the contextvars state again, it goes away. # a=None is printed due to the key_order argument passed to # KeyValueRenderer, but it is NOT present anymore. clear_contextvars() log.info("hi there") ``` -------------------------------- ### Basic Bound Logger Usage Source: https://github.com/hynek/structlog/blob/main/docs/bound-loggers.md Illustrates the fundamental usage of a bound logger, including getting a logger, binding context, and logging messages. This shows the core workflow of structlog. ```python import structlog # Get a logger instance logger = structlog.get_logger() # Bind some context bound_logger = logger.bind(user_id=123, request_id='abc') # Log a message with additional context bound_logger.info("User logged in", username='testuser') # Log another message, context is preserved bound_logger.debug("Processing request") # Unbind context to create a logger with less context unbound_logger = bound_logger.unbind('user_id') unbound_logger.info("Operation completed") ``` -------------------------------- ### Wrap Dictionary for Thread-Local Storage with structlog Source: https://github.com/hynek/structlog/blob/main/docs/thread-local.md Demonstrates how to use `structlog.threadlocal.wrap_dict` to create a dictionary-like class suitable for thread-local storage. Instances of this class share common data within a thread, ensuring consistent context across logger instances. The example shows instantiation, modification, and comparison of these wrapped dictionaries. ```python from structlog.threadlocal import wrap_dict WrappedDictClass = wrap_dict(dict) d1 = WrappedDictClass({"a": 1}) d2 = WrappedDictClass({"b": 2}) d3 = WrappedDictClass() d3["c"] = 3 print(d1 == d2 == d3 == WrappedDictClass()) print(d3) ``` -------------------------------- ### Using merge_threadlocal Processor in structlog Source: https://github.com/hynek/structlog/blob/main/docs/thread-local.md This example illustrates the recommended flow for using the `merge_threadlocal` processor. It involves configuring structlog with this processor, clearing the thread-local context, binding variables, and then logging messages, which will automatically include the bound thread-local data. ```python # Configure structlog with merge_threadlocal as the first processor structlog.configure( processors=[ structlog.threadlocal.merge_threadlocal, # ... other processors ] ) # Clear thread-local context at the start of a request handler structlog.threadlocal.clear_threadlocal() # Bind variables to the thread-local context structlog.threadlocal.bind_threadlocal(user_id=123, request_id='abc') # Log messages normally; thread-local binds will be merged logger = structlog.get_logger() logger.info('User logged in') # Access thread-local storage if needed current_context = structlog.threadlocal.get_threadlocal() merged_context = structlog.threadlocal.get_merged_threadlocal() ``` -------------------------------- ### Set up JSON Logging with Python-JSON-Logger Source: https://github.com/hynek/structlog/blob/main/docs/standard-library.md Configures the standard library's logging to output JSON logs using the python-json-logger library. This setup ensures that both structlog and standard logging messages are formatted as JSON. ```python import logging import sys from pythonjsonlogger import jsonlogger handler = logging.StreamHandler(sys.stdout) handler.setFormatter(jsonlogger.JsonFormatter()) root_logger = logging.getLogger() root_logger.addHandler(handler) ``` -------------------------------- ### Basic Logging in a View Source: https://github.com/hynek/structlog/blob/main/docs/getting-started.md Illustrates a naive approach to logging within a web view, highlighting the repetition of context parameters. ```python def view(request): user_agent = request.get("HTTP_USER_AGENT", "UNKNOWN") peer_ip = request.client_addr if something: log.info("something", user_agent=user_agent, peer_ip=peer_ip) return "something" elif something_else: log.info("something_else", user_agent=user_agent, peer_ip=peer_ip) return "something_else" else: log.info("else", user_agent=user_agent, peer_ip=peer_ip) return "else" ``` -------------------------------- ### Structlog Configuration for Testing Source: https://github.com/hynek/structlog/blob/main/docs/recipes.md Sets up structlog with KeyValueRenderer for testing purposes and resets defaults afterwards. ```python import structlog structlog.configure( processors=[structlog.processors.KeyValueRenderer()], ) ``` ```python import structlog structlog.reset_defaults() ``` -------------------------------- ### Basic Logging with Structlog Source: https://github.com/hynek/structlog/blob/main/docs/why.md Demonstrates basic key-value logging and string interpolation using structlog's get_logger. It shows how to log events with associated key-value pairs and also supports traditional string formatting. ```python from structlog import get_logger log = get_logger() log.info("key_value_logging", out_of_the_box=True, effort=0) log.info("Hello, %s!", "world") log.info("Hello, %(name)s!", {"name": "world"}) ``` -------------------------------- ### Logging with Bound Context in a View Source: https://github.com/hynek/structlog/blob/main/docs/getting-started.md Demonstrates a more efficient approach using structlog's bind method to attach context to the logger, reducing repetition. ```python def view(request): log = log.bind( user_agent=request.get("HTTP_USER_AGENT", "UNKNOWN"), peer_ip=request.client_addr, ) if foo := request.get("foo"): log = log.bind(foo=foo) if something: log.info("something") return "something" elif something_else: log.info("something_else") return "something_else" else: log.info("else") return "else" ``` -------------------------------- ### Custom Processor for Structlog Source: https://github.com/hynek/structlog/blob/main/docs/why.md Provides an example of a custom processor function for structlog. Processors are functions that manipulate event dictionaries in a pipeline, allowing for custom data enrichment like adding timestamps. ```python import time def timestamper(logger, log_method, event_dict): """Add a timestamp to each log entry.""" event_dict["timestamp"] = time.time() return event_dict ``` -------------------------------- ### Capturing Log Calls with CapturingLogger Source: https://github.com/hynek/structlog/blob/main/docs/api.rst Demonstrates how to use CapturingLogger to capture log messages and their arguments. Useful for testing and debugging. ```python from pprint import pprint cl = structlog.testing.CapturingLogger() cl.info("hello") cl.info("hello", when="again") pprint(cl.calls) ``` -------------------------------- ### Reset structlog Defaults Source: https://github.com/hynek/structlog/blob/main/docs/thread-local.md This snippet shows how to reset structlog to its default configuration. This is commonly used in test cleanup routines to ensure that subsequent tests start with a clean slate. ```python import structlog structlog.reset_defaults() ``` -------------------------------- ### Advanced Logging with dictConfig for Console and File Output Source: https://github.com/hynek/structlog/blob/main/docs/standard-library.md Demonstrates using `logging.config.dictConfig` to set up sophisticated logging. It configures two handlers: one for colored console output and another for plain text file output, both using `structlog.stdlib.ProcessorFormatter`. ```python import logging.config import structlog def extract_from_record(_, __, event_dict): """ Extract thread and process names and add them to the event dict. """ record = event_dict["_record"] event_dict["thread_name"] = record.threadName event_dict["process_name"] = record.processName return event_dict logging.config.dictConfig( { "version": 1, "disable_existing_loggers": False, "formatters": { "plain": { "()": structlog.stdlib.ProcessorFormatter, "processors": [ structlog.stdlib.ProcessorFormatter.remove_processors_meta, structlog.dev.ConsoleRenderer(colors=False), ], "foreign_pre_chain": [ structlog.stdlib.add_log_level, structlog.stdlib.ExtraAdder(), structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M:%S"), ], }, "colored": { "()": structlog.stdlib.ProcessorFormatter, "processors": [ extract_from_record, structlog.stdlib.ProcessorFormatter.remove_processors_meta, structlog.dev.ConsoleRenderer(colors=True), ], "foreign_pre_chain": [ structlog.stdlib.add_log_level, structlog.stdlib.ExtraAdder(), structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M:%S"), ], }, }, "handlers": { "default": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "colored", }, "file": { "level": "DEBUG", "class": "logging.handlers.WatchedFileHandler", "filename": "test.log", "formatter": "plain", }, }, "loggers": { "": { "handlers": ["default", "file"], "level": "DEBUG", } } } ) ``` -------------------------------- ### Asyncio Logging with Structlog Source: https://github.com/hynek/structlog/blob/main/docs/getting-started.md Demonstrates using structlog's asynchronous logging methods within an asyncio application. The sync and async methods can be used interchangeably. ```python >>> import asyncio >>> logger = structlog.get_logger() >>> async def f(): ... await logger.ainfo("async hi!") ... >>> logger.info("Loop isn't running yet, but we can log!") 2023-04-06 07:25:48 [info ] Loop isn't running yet, but we can log! >>> asyncio.run(f()) 2023-04-06 07:26:08 [info ] async hi! ``` -------------------------------- ### Structlog Log Level Filtering Example (Python) Source: https://github.com/hynek/structlog/blob/main/docs/bound-loggers.md Illustrates how to configure structlog to filter log messages based on their level using structlog.make_filtering_bound_logger. It shows the effect of filtering by comparing output before and after setting the logging level. ```python import structlog import logging logger = structlog.get_logger() # Log before filtering logger.debug("This message will be logged.") # Configure filtering to INFO level structlog.configure(wrapper_class=structlog.make_filtering_bound_logger(logging.INFO)) # Log after filtering logger.debug("This message will NOT be logged.") ``` -------------------------------- ### Binding Context Variables Globally Source: https://github.com/hynek/structlog/blob/main/docs/getting-started.md Shows how to use structlog's contextvars to bind context that is available across different parts of an application, like a peer IP address. ```python >>> structlog.contextvars.bind_contextvars(peer_ip="1.2.3.4") >>> structlog.get_logger().info("something") 2022-10-10 10:18:05 [info ] something peer_ip=1.2.3.4 ``` -------------------------------- ### structlog.configure with dict_tracebacks and JSONRenderer Source: https://github.com/hynek/structlog/blob/main/docs/api.rst Configures structlog to use dict_tracebacks for structured exception logging and JSONRenderer for output. Demonstrates logging an exception. ```APIDOC ## structlog.configure with dict_tracebacks and JSONRenderer ### Description Configures structlog to use `dict_tracebacks` for structured exception logging and `JSONRenderer` for output. Demonstrates logging an exception. ### Method N/A (Configuration and Logging) ### Endpoint N/A ### Parameters N/A ### Request Example ```python structlog.configure( processors=[ structlog.processors.dict_tracebacks, structlog.processors.JSONRenderer(), ], ) log = structlog.get_logger() var = "spam" try: 1 / 0 except ZeroDivisionError: log.exception("Cannot compute!") ``` ### Response #### Success Response (Log Output) ```json {"event": "Cannot compute!", "exception": [{"exc_type": "ZeroDivisionError", "exc_value": "division by zero", "exc_notes": [], "syntax_error": null, "is_cause": false, "frames": [{"filename": "", "lineno": 2, "name": "", "locals": {..., "var": "'spam'"}}], "is_group": false, "exceptions": []}]} ``` ``` -------------------------------- ### Redacting Sensitive Locals in Exception Tracebacks Source: https://github.com/hynek/structlog/blob/main/docs/recipes.md This example demonstrates how to subclass `ExceptionDictTransformer` to redact specific keys like 'token' and 'password' from the 'locals' dictionary within exception frames. It defines helper functions to process locals and frames before applying the custom transformer. ```python from structlog.tracebacks import ExceptionDictTransformer def redact_locals(frame_locals): return { k: (v if k not in ("token", "password") else "") for k, v in frame_locals.items() } def redact_frames(exc_dict): for frame in exc_dict["frames"]: if "locals" in frame: frame["locals"] = redact_locals(frame["locals"]) return exc_dict class RedactingExceptionDictTransformer(ExceptionDictTransformer): def __call__(self, exc_info): exceptions = super().__call__(exc_info) return [redact_frames(exc) for exc in exceptions] ``` -------------------------------- ### Configure Structlog for Standard Library Logging Source: https://github.com/hynek/structlog/blob/main/docs/standard-library.md Configures structlog to use standard library logging processors. This setup allows structlog to build event dictionaries and pass them to the standard library's logging methods, where they can be further processed and formatted. ```python import structlog structlog.configure( processors=[ structlog.stdlib.filter_by_level, structlog.stdlib.add_logger_name, structlog.stdlib.add_log_level, structlog.stdlib.PositionalArgumentsFormatter(), structlog.processors.StackInfoRenderer(), structlog.processors.format_exc_info, structlog.processors.UnicodeDecoder(), # Transform event dict into `logging.Logger` method arguments. # "event" becomes "msg" and the rest is passed as a dict in # "extra". IMPORTANT: This means that the standard library MUST # render "extra" for the context to appear in log entries! See # warning below. structlog.stdlib.render_to_log_kwargs, ], logger_factory=structlog.stdlib.LoggerFactory(), wrapper_class=structlog.stdlib.BoundLogger, cache_logger_on_first_use=True, ) ``` -------------------------------- ### Wrap Logger Manually with Custom Processor (Python) Source: https://github.com/hynek/structlog/blob/main/docs/bound-loggers.md Demonstrates wrapping a custom logger with structlog.wrap_logger, including a custom processor function. This allows for manual configuration without relying on global structlog settings. The example shows binding and unbinding context to the logger. ```python import structlog class CustomPrintLogger: def msg(self, message): print(message) def proc(logger, method_name, event_dict): print("I got called with", event_dict) return repr(event_dict) log = structlog.wrap_logger( CustomPrintLogger(), wrapper_class=structlog.BoundLogger, processors=[proc], ) log2 = log.bind(x=42) log.msg("hello world") log2.msg("hello world") log3 = log2.unbind("x") log3.msg("nothing bound anymore", foo="but you can structure the event too") ``` -------------------------------- ### Configure structlog with ProcessorFormatter for standard logging Source: https://github.com/hynek/structlog/blob/main/docs/standard-library.md This code snippet demonstrates the simplest configuration for using structlog.stdlib.ProcessorFormatter. It sets up structlog to prepare event dictionaries for the formatter and then initializes the formatter with a ConsoleRenderer. A StreamHandler is also created, ready to be attached to a logger. ```python import logging import structlog structlog.configure( processors=[ # Prepare event dict for `ProcessorFormatter`. structlog.stdlib.ProcessorFormatter.wrap_for_formatter, ], logger_factory=structlog.stdlib.LoggerFactory(), ) formatter = structlog.stdlib.ProcessorFormatter( processors=[structlog.dev.ConsoleRenderer()], ) handler = logging.StreamHandler() ``` -------------------------------- ### structlog.twisted.PlainFileLogObserver Source: https://github.com/hynek/structlog/blob/main/docs/api.rst Documentation for the PlainFileLogObserver class in structlog.twisted, used for observing logs and writing them to a file. ```APIDOC ## structlog.twisted.PlainFileLogObserver ### Description An observer that writes log events to a specified file. It is designed for use within the Twisted framework and can be configured for plain text or structured output. ### Usage Initialize with a file path or file-like object and integrate with structlog's configuration. ``` -------------------------------- ### Using Structlog with Type Hints (Python) Source: https://github.com/hynek/structlog/blob/main/docs/typing.md Demonstrates how to use structlog with static type hints in Python. It shows how to annotate a logger instance with `structlog.stdlib.BoundLogger` and highlights type checking behavior with Mypy for methods like `info` and `msg`. ```python import structlog logger: structlog.stdlib.BoundLogger = structlog.get_logger() logger.info("hi") # <- ok logger.msg("hi") # <- Mypy: 'error: "BoundLogger" has no attribute "msg"' ``` -------------------------------- ### Configure structlog with DictTracebacks and JSONRenderer Source: https://github.com/hynek/structlog/blob/main/docs/api.rst Configures structlog to include structured tracebacks for exceptions and render logs as JSON. Useful for detailed error logging. ```python >>> structlog.configure( ... processors=[ ... structlog.processors.dict_tracebacks, ... structlog.processors.JSONRenderer(), ... ], ... ) >>> log = structlog.get_logger() >>> var = "spam" >>> try: ... 1 / 0 ... except ZeroDivisionError: ... log.exception("Cannot compute!") {"event": "Cannot compute!", "exception": [{"exc_type": "ZeroDivisionError", "exc_value": "division by zero", "exc_notes": [], "syntax_error": null, "is_cause": false, "frames": [{"filename": "", "lineno": 2, "name": "", "locals": {..., "var": "'spam'"}}], "is_group": false, "exceptions": []}]} ``` -------------------------------- ### Bind Request Data to Logs in Flask with Structlog Source: https://github.com/hynek/structlog/blob/main/docs/contextvars.md This Python code demonstrates how to bind request-specific data (request ID, URL path, peer IP) to structlog log entries within a Flask application. It utilizes `structlog.contextvars` to manage this data, ensuring it's automatically included in all logs generated during a request. The setup involves configuring structlog processors and a basic Flask app with a route. ```python import logging import sys import uuid import flask from .some_module import some_function import structlog logger = structlog.get_logger() app = flask.Flask(__name__) @app.route("/login", methods=["POST", "GET"]) def some_route(): # You would put this into some kind of middleware or processor so it's set # automatically for all requests in all views. structlog.contextvars.clear_contextvars() structlog.contextvars.bind_contextvars( view=flask.request.path, request_id=str(uuid.uuid4()), peer=flask.request.access_route[0], ) # End of belongs-to-middleware. log = logger.bind() # do something # ... log.info("user logged in", user="test-user") # ... some_function() # ... return "logged in!" if __name__ == "__main__": logging.basicConfig( format="%(message)s", stream=sys.stdout, level=logging.INFO ) structlog.configure( processors=[ structlog.contextvars.merge_contextvars, # <--!!! structlog.processors.KeyValueRenderer( key_order=["event", "view", "peer"] ), ], logger_factory=structlog.stdlib.LoggerFactory(), ) app.run() ``` -------------------------------- ### Structlog Basic Logging Flow (Python) Source: https://github.com/hynek/structlog/blob/main/docs/bound-loggers.md Demonstrates the core steps of structlog logging: binding context, event dictionary creation, processor chain execution, and rendering. It assumes default configuration and shows how event data is transformed before being passed to the wrapped logger. ```python import structlog logger = structlog.get_logger() log = logger.bind(foo="bar") log.info("Hello, %s!", "world", number=42) ``` -------------------------------- ### PrintLoggerFactory Class Source: https://github.com/hynek/structlog/blob/main/docs/api.rst A factory for creating PrintLogger instances. ```APIDOC ## PrintLoggerFactory ### Description A factory for creating `PrintLogger` instances. ``` -------------------------------- ### LogfmtRenderer with custom formatting Source: https://github.com/hynek/structlog/blob/main/docs/api.rst Renders a dictionary in logfmt format. Allows custom key order and controls boolean rendering. ```python >>> from structlog.processors import LogfmtRenderer >>> event_dict = {"a": 42, "b": [1, 2, 3], "flag": True} >>> LogfmtRenderer(sort_keys=True)(None, "", event_dict) 'a=42 b="[1, 2, 3]" flag' >>> LogfmtRenderer(key_order=["b", "a"], bool_as_flag=False)(None, "", event_dict) 'b="[1, 2, 3]" a=42 flag=true' ``` -------------------------------- ### structlog.contextvars Module Source: https://github.com/hynek/structlog/blob/main/docs/api.rst Utilities for managing context variables using contextvars. ```APIDOC ## bind_contextvars ### Description Binds context variables. ### Signature `structlog.contextvars.bind_contextvars(**context)` ## bound_contextvars ### Description Returns a dictionary of bound context variables. ### Signature `structlog.contextvars.bound_contextvars(**new_event_dict)` ## get_contextvars ### Description Returns a dictionary of context variables. ### Signature `structlog.contextvars.get_contextvars()` ## get_merged_contextvars ### Description Returns merged context variables. ### Signature `structlog.contextvars.get_merged_contextvars(**new_event_dict)` ## merge_contextvars ### Description Merges context variables into an event dictionary. ### Signature `structlog.contextvars.merge_contextvars(logger, method_name, event_dict)` ## clear_contextvars ### Description Clears all context variables. ### Signature `structlog.contextvars.clear_contextvars()` ## unbind_contextvars ### Description Unbinds context variables. ### Signature `structlog.contextvars.unbind_contextvars(*keys)` ## reset_contextvars ### Description Resets context variables. ### Signature `structlog.contextvars.reset_contextvars()` ``` -------------------------------- ### JSON Rendering with Custom Serialization Source: https://github.com/hynek/structlog/blob/main/docs/api.rst Shows how to use JSONRenderer to serialize log events. It demonstrates custom serialization using a `__structlog__` method and falls back to `repr()` if the method is not defined. ```python from structlog.processors import JSONRenderer JSONRenderer(sort_keys=True)(None, "", {"a": 42, "b": [1, 2, 3]}) ``` ```python class C1: def __structlog__(self): return ["C1!"] def __repr__(self): return "__structlog__ took precedence" class C2: def __repr__(self): return "No __structlog__, so this is used." from structlog.processors import JSONRenderer JSONRenderer(sort_keys=True)(None, "", {"c1": C1(), "c2": C2()}) ``` -------------------------------- ### WriteLoggerFactory Class Source: https://github.com/hynek/structlog/blob/main/docs/api.rst A factory for creating WriteLogger instances. ```APIDOC ## WriteLoggerFactory ### Description A factory for creating `WriteLogger` instances. ``` -------------------------------- ### Asyncio Logging with Structlog Source: https://github.com/hynek/structlog/blob/main/docs/standard-library.md Demonstrates how to use asynchronous logging methods in structlog for asyncio applications. These methods, prefixed with 'a' (e.g., ainfo), process logs in a thread pool to prevent blocking the application. ```python # Example usage within an asyncio application: # await logger.ainfo("event!") ``` -------------------------------- ### Checking and Configuring structlog Source: https://github.com/hynek/structlog/blob/main/docs/configuration.md Shows how to check if structlog is configured using `structlog.is_configured()`, configure it with a specific logger factory (e.g., `structlog.stdlib.LoggerFactory`), and retrieve the current configuration using `structlog.get_config()`. ```python from structlog import get_logger, configure, get_config, is_configured from structlog.stdlib import LoggerFactory print(is_configured()) configure(logger_factory=LoggerFactory()) print(is_configured()) cfg = get_config() print(cfg["logger_factory"]) ``` -------------------------------- ### Using structlog with Standard Library Logging Source: https://github.com/hynek/structlog/blob/main/docs/configuration.md Illustrates how to configure structlog to use Python's standard library `logging` module for output. This involves setting the `logger_factory` to `structlog.stdlib.LoggerFactory` and then obtaining a logger. ```python from structlog import get_logger, configure from structlog.stdlib import LoggerFactory configure(logger_factory=LoggerFactory()) log = get_logger() log.critical("this is too easy!") ``` -------------------------------- ### format_exc_info Source: https://github.com/hynek/structlog/blob/main/docs/api.rst Formats exception information into a dictionary suitable for logging. ```APIDOC ## format_exc_info ### Description Formats exception information into a dictionary suitable for logging. ### Method N/A (Processor Function) ### Endpoint N/A ### Parameters N/A (Assumes `exc_info` is present in the event dictionary) ### Request Example ```python from structlog.processors import format_exc_info try: raise ValueError except ValueError: # The `exc_info=True` is typically added by log.exception() # This example manually creates the event dict for demonstration formatted_exc = format_exc_info(None, "", {"exc_info": True}) print(formatted_exc) ``` ### Response #### Success Response (Dictionary Output) ```python {'exception': 'Traceback (most recent call last):\n File "", line 3, in \nValueError'} ``` ``` -------------------------------- ### structlog.dev Module Source: https://github.com/hynek/structlog/blob/main/docs/api.rst Utilities for development and debugging, including console rendering. ```APIDOC ## ConsoleRenderer ### Description Renders log events for console output, with support for colors and columns. ### Methods - **get_default_level_styles(**`**kwargs)`: Returns default styles for log levels. - **get_default_column_styles(**`**kwargs)`: Returns default styles for columns. ### Attributes - **exception_formatter**: Formatter for exceptions. - **sort_keys**: Whether to sort keys in the output. - **columns**: List of columns to display. - **get_active**: Returns the active console renderer. - **event_key**: The key used for the event message. - **timestamp_key**: The key used for the timestamp. - **level_styles**: Styles for log levels. - **colors**: Whether to use colors. - **force_colors**: Whether to force color usage. - **repr_native_str**: Whether to use native string representation for repr. - **pad_level**: Padding for the log level column. - **pad_event_to**: Padding for the event message column. ## ColumnStyles ### Description Defines styles for different columns in console output. ## Column ### Description Represents a column in the console output. ## ColumnFormatter(typing.Protocol) ### Description Protocol for column formatters. ### Methods - **__call__(**`context`, `logger`, `event_dict)`: Formats a column's content. ## KeyValueColumnFormatter ### Description Formatter for key-value pairs in columns. ## LogLevelColumnFormatter ### Description Formatter for the log level column. ## plain_traceback ### Description Formats a traceback in a plain text format. ### Signature `structlog.dev.plain_traceback(exc_info)` ## rich_traceback ### Description Formats a traceback using rich text formatting. ### Signature `structlog.dev.rich_traceback(exc_info, **kwargs)` ## rich_monochrome_traceback ### Description Formats a traceback in monochrome using rich text formatting. ### Signature `structlog.dev.rich_monochrome_traceback(exc_info, **kwargs)` ## better_traceback ### Description Provides an enhanced traceback formatting. ### Signature `structlog.dev.better_traceback(exc_info, **kwargs)` ## set_exc_info ### Description Sets exception information for structlog. ### Signature `structlog.dev.set_exc_info(exc_info)` ``` -------------------------------- ### structlog.twisted.BoundLogger Methods Source: https://github.com/hynek/structlog/blob/main/docs/api.rst Provides documentation for the methods available on the BoundLogger class within the structlog.twisted module, which are essential for logging in Twisted applications. ```APIDOC ## structlog.twisted.BoundLogger ### Description Represents a bound logger for use within the Twisted framework. It allows for contextual logging and provides methods for common logging operations. ### Methods - **bind(key, value)**: Binds a key-value pair to the logger's context. - **unbind(key)**: Removes a key from the logger's context. - **new(**context**)**: Creates a new bound logger with the provided context merged with the existing context. - **msg(event, **kwargs**)**: Logs a message with the given event and additional keyword arguments. - **err(event, **kwargs**)**: Logs an error message with the given event and additional keyword arguments. ``` -------------------------------- ### Configuring Structlog with a Timestamper and KeyValueRenderer Source: https://github.com/hynek/structlog/blob/main/docs/getting-started.md Configures structlog to use the custom timestamper processor followed by the KeyValueRenderer for output. ```python >>> structlog.configure(processors=[timestamper, structlog.processors.KeyValueRenderer()]) >>> structlog.get_logger().info("hi") # doctest: +SKIP event='hi' time='2018-01-21T09:37:36.976816' ``` -------------------------------- ### BytesLoggerFactory Class Source: https://github.com/hynek/structlog/blob/main/docs/api.rst A factory for creating BytesLogger instances. ```APIDOC ## BytesLoggerFactory ### Description A factory for creating `BytesLogger` instances. ``` -------------------------------- ### Configuring Structlog with JSONRenderer Source: https://github.com/hynek/structlog/blob/main/docs/getting-started.md Configures structlog to use the JSONRenderer, suitable for log aggregation systems. ```python >>> structlog.configure(processors=[structlog.processors.JSONRenderer()]) >>> structlog.get_logger().info("hi") {"event": "hi"} ``` -------------------------------- ### get_context Source: https://github.com/hynek/structlog/blob/main/docs/api.rst Retrieves the current context variables. ```APIDOC ## get_context ### Description Retrieves the current context variables. ### Signature `structlog.get_context(logger)` ``` -------------------------------- ### Structlog Default Configuration Source: https://github.com/hynek/structlog/blob/main/docs/getting-started.md This code shows the default configuration for structlog, including processors, wrapper class, context class, logger factory, and cache settings. ```python import logging import structlog structlog.configure( processors=[ structlog.contextvars.merge_contextvars, structlog.processors.add_log_level, structlog.processors.StackInfoRenderer(), structlog.dev.set_exc_info, structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M:%S", utc=False), structlog.dev.ConsoleRenderer() ], wrapper_class=structlog.make_filtering_bound_logger(logging.NOTSET), context_class=dict, logger_factory=structlog.PrintLoggerFactory(), cache_logger_on_first_use=False ) log = structlog.get_logger() ``` -------------------------------- ### structlog.testing Module Source: https://github.com/hynek/structlog/blob/main/docs/api.rst Utilities for testing structlog integrations. ```APIDOC ## capture_logs ### Description A decorator that captures log events. ### Signature `structlog.testing.capture_logs(logger)` ## LogCapture ### Description An object that captures log events. ## CapturingLogger ### Description A logger that captures calls made to it. ### Example ```python >>> from pprint import pprint >>> cl = structlog.testing.CapturingLogger() >>> cl.info("hello") >>> cl.info("hello", when="again") >>> pprint(cl.calls) [CapturedCall(method_name='info', args=('hello',), kwargs={}), CapturedCall(method_name='info', args=('hello',), kwargs={'when': 'again'})] ``` ## CapturingLoggerFactory ### Description A factory for creating `CapturingLogger` instances. ## CapturedCall ### Description Represents a captured log call. ## ReturnLogger ### Description A logger that returns a predefined value for each log method. ### Methods - **msg(**`event_dict)` - **err(**`event_dict)` - **debug(**`event_dict)` - **info(**`event_dict)` - **warning(**`event_dict)` - **error(**`event_dict)` - **critical(**`event_dict)` - **log(**`level`, `event_dict)` - **failure(**`event_dict)` - **fatal(**`event_dict)` ## ReturnLoggerFactory ### Description A factory for creating `ReturnLogger` instances. ``` -------------------------------- ### structlog.stdlib.render_to_log_kwargs Source: https://github.com/hynek/structlog/blob/main/docs/api.rst Renders event dictionary into keyword arguments suitable for standard library loggers. ```APIDOC ## structlog.stdlib.render_to_log_kwargs ### Description Renders event dictionary into keyword arguments suitable for standard library loggers. ### Method N/A (Processor Function) ### Endpoint N/A ### Parameters N/A ### Request Example ```python import structlog # Assuming a configured logger and event_dict # This processor is typically part of the structlog configuration pipeline. # Example usage within a pipeline: # structlog.configure( # processors=[ # ..., # structlog.stdlib.render_to_log_kwargs # ] # ) ``` ### Response N/A (Modifies event dictionary for subsequent processors) ``` -------------------------------- ### Render Log Arguments to Logback Args and Kwargs Source: https://github.com/hynek/structlog/blob/main/docs/standard-library.md Renders the event dictionary into positional and keyword arguments for logging.Logger logging methods. This is useful if you want to render your log entries entirely within logging. ```python from structlog.stdlib import render_to_log_args_and_kwargs # Example usage (within a structlog configuration): structlog.configure( processors=[ # ... other processors render_to_log_args_and_kwargs ], # ... other configuration ) ``` -------------------------------- ### Flask: Connect Request Details Signal Handler Source: https://github.com/hynek/structlog/blob/main/docs/frameworks.md Connects the `bind_request_details` function to Flask's `request_started` signal. This ensures that the request details are bound to structlog's context variables every time a request begins processing. ```python from flask import request_started request_started.connect(bind_request_details, app) ``` -------------------------------- ### BoundLogger Class Source: https://github.com/hynek/structlog/blob/main/docs/api.rst Represents a logger instance with bound context variables. ```APIDOC ## BoundLogger ### Description A logger instance that has context variables bound to it. ### Methods - **new(**`*args`, `**kwargs)`: Creates a new bound logger with additional context. - **bind(**`**new_attributes)`: Binds new key-value pairs to the logger's context. - **unbind(**`*keys_to_remove)`: Removes specified keys from the logger's context. ``` -------------------------------- ### Create Local Logger for Frequent Logging Source: https://github.com/hynek/structlog/blob/main/docs/performance.md When logging frequently without binding, create a local logger instance to avoid expensive global scope lookups. This is particularly useful within loops. ```python logger = structlog.get_logger() def f(): log = logger.bind() for i in range(1000000000): log.info("iterated", i=i) ``` -------------------------------- ### format_exc_info processor Source: https://github.com/hynek/structlog/blob/main/docs/api.rst Formats exception information into a dictionary suitable for logging. Use when 'exc_info' is True in the event dictionary. ```python >>> from structlog.processors import format_exc_info >>> try: ... raise ValueError ... except ValueError: ... format_exc_info(None, "", {"exc_info": True}) # doctest: +ELLIPSIS {'exception': 'Traceback (most recent call last):...' ```