0
# Structlog
1
2
Structured logging for Python that emphasizes simplicity, power, and performance. Structlog uses a function-based approach where everything revolves around functions that take and return dictionaries, all hidden behind familiar APIs. It offers flexible output formatting with built-in support for JSON, logfmt, and pretty console output, while allowing users to choose whether structlog handles log output directly or forwards entries to existing logging systems.
3
4
## Package Information
5
6
- **Package Name**: structlog
7
- **Language**: Python
8
- **Installation**: `pip install structlog`
9
10
## Core Imports
11
12
```python
13
import structlog
14
```
15
16
Common usage patterns:
17
18
```python
19
# For basic configuration and logger creation
20
from structlog import configure, get_logger
21
22
# For specific components
23
from structlog import processors, dev, stdlib, testing
24
25
# For context management - import specific functions
26
from structlog.contextvars import bind_contextvars, get_contextvars, bound_contextvars
27
28
# For development tools
29
from structlog.dev import ConsoleRenderer
30
31
# For testing
32
from structlog.testing import capture_logs, ReturnLoggerFactory
33
```
34
35
## Basic Usage
36
37
```python
38
import structlog
39
40
# Configure structlog (typically done once at application startup)
41
structlog.configure(
42
processors=[
43
structlog.processors.TimeStamper(fmt="iso"),
44
structlog.dev.ConsoleRenderer()
45
],
46
wrapper_class=structlog.stdlib.BoundLogger,
47
logger_factory=structlog.stdlib.LoggerFactory(),
48
cache_logger_on_first_use=True,
49
)
50
51
# Get a logger
52
logger = structlog.get_logger()
53
54
# Use the logger with structured data
55
logger.info("User logged in", user_id=123, username="alice")
56
57
# Bind context that persists across log calls
58
logger = logger.bind(user_id=123, session_id="abc-def")
59
logger.info("Action performed", action="file_upload")
60
logger.warning("Rate limit approaching", remaining_requests=5)
61
62
# Create new logger with cleared context
63
logger = logger.new(request_id="xyz-789")
64
logger.error("Processing failed", error_code="INVALID_INPUT")
65
```
66
67
## Architecture
68
69
Structlog's architecture is built around three key concepts:
70
71
- **Processors**: Functions that transform log entries as they flow through the logging pipeline
72
- **Loggers**: Wrapped logger instances that provide the external API and maintain context
73
- **Context**: Immutable dictionaries that carry structured data with each log entry
74
75
The design allows maximum flexibility - you can use structlog as a pure structured logging library, integrate it with Python's standard logging module, or adapt it to any existing logging system.
76
77
## Capabilities
78
79
### Configuration and Setup
80
81
Global configuration system for setting up processors, logger factories, and wrapper classes. Controls how structlog initializes loggers and processes log events throughout the application.
82
83
```python { .api }
84
def configure(
85
processors=None,
86
wrapper_class=None,
87
context_class=None,
88
logger_factory=None,
89
cache_logger_on_first_use=None
90
) -> None: ...
91
92
def configure_once(**kwargs) -> None: ...
93
def get_config() -> dict[str, Any]: ...
94
def is_configured() -> bool: ...
95
def reset_defaults() -> None: ...
96
```
97
98
[Configuration](./configuration.md)
99
100
### Logger Creation and Wrapping
101
102
Core functions for creating and wrapping loggers, providing the main entry points for getting configured logger instances and wrapping existing loggers.
103
104
```python { .api }
105
def get_logger(*args, **initial_values) -> Any: ...
106
def getLogger(*args, **initial_values) -> Any: ...
107
def wrap_logger(
108
logger,
109
processors=None,
110
wrapper_class=None,
111
context_class=None,
112
cache_logger_on_first_use=None,
113
logger_factory_args=None,
114
**initial_values
115
) -> Any: ...
116
```
117
118
[Logger Creation](./logger-creation.md)
119
120
### Bound Logger Classes
121
122
Immutable context-carrying logger classes that provide the core structlog API with context binding, unbinding, and delegation to wrapped loggers.
123
124
```python { .api }
125
class BoundLoggerBase:
126
def bind(**new_values) -> Self: ...
127
def unbind(*keys) -> Self: ...
128
def try_unbind(*keys) -> Self: ...
129
def new(**new_values) -> Self: ...
130
131
class BoundLogger(BoundLoggerBase): ...
132
133
def get_context(bound_logger) -> Context: ...
134
```
135
136
[Bound Loggers](./bound-loggers.md)
137
138
### Log Processors
139
140
Extensible pipeline of functions that transform, filter, and format log events. Includes built-in processors for timestamps, JSON/logfmt rendering, exception handling, and more.
141
142
```python { .api }
143
class TimeStamper:
144
def __init__(self, fmt=None, utc=True, key="timestamp"): ...
145
def __call__(self, logger, name, event_dict) -> EventDict: ...
146
147
class MaybeTimeStamper:
148
def __init__(self, fmt=None, utc=True, key="timestamp"): ...
149
def __call__(self, logger, name, event_dict) -> EventDict: ...
150
151
class JSONRenderer:
152
def __init__(self, serializer=json.dumps, **dumps_kw): ...
153
def __call__(self, logger, name, event_dict) -> str | bytes: ...
154
155
class LogfmtRenderer:
156
def __init__(self, key_order=None, drop_missing=False, repr_native_str=True): ...
157
def __call__(self, logger, method_name, event_dict) -> str: ...
158
159
class KeyValueRenderer:
160
def __init__(self, sort_keys=False, key_order=None, drop_missing=False, repr_native_str=True): ...
161
def __call__(self, logger, method_name, event_dict) -> str: ...
162
163
class ExceptionPrettyPrinter:
164
def __init__(self, file=None): ...
165
def __call__(self, logger, name, event_dict) -> EventDict: ...
166
```
167
168
[Processors](./processors.md)
169
170
### Development Tools
171
172
Rich console output, colored logging, column formatting, and advanced traceback rendering designed for development environments and debugging.
173
174
```python { .api }
175
class ConsoleRenderer:
176
def __init__(
177
self,
178
pad_event=30,
179
colors=True,
180
force_colors=False,
181
repr_native_str=False,
182
level_styles=None,
183
exception_formatter=...,
184
sort_keys=True,
185
event_key="event",
186
timestamp_key="timestamp",
187
columns=None,
188
pad_level=True
189
): ...
190
def __call__(self, logger, name, event_dict) -> str: ...
191
```
192
193
[Development Tools](./development-tools.md)
194
195
### Standard Library Integration
196
197
Complete integration with Python's standard logging module, including stdlib-compatible loggers, formatters, and processors for bridging structlog with existing logging infrastructure.
198
199
```python { .api }
200
class BoundLogger(BoundLoggerBase):
201
def debug(self, event=None, **kw) -> None: ...
202
def info(self, event=None, **kw) -> None: ...
203
def warning(self, event=None, **kw) -> None: ...
204
def error(self, event=None, **kw) -> None: ...
205
def critical(self, event=None, **kw) -> None: ...
206
def exception(self, event=None, **kw) -> None: ...
207
208
class AsyncBoundLogger:
209
async def adebug(self, event: str, *args, **kw) -> None: ...
210
async def ainfo(self, event: str, *args, **kw) -> None: ...
211
async def awarning(self, event: str, *args, **kw) -> None: ...
212
async def aerror(self, event: str, *args, **kw) -> None: ...
213
async def acritical(self, event: str, *args, **kw) -> None: ...
214
async def aexception(self, event: str, *args, **kw) -> None: ...
215
216
class ProcessorFormatter(logging.Formatter):
217
def __init__(self, processor, foreign_pre_chain=None, keep_exc_info=False, keep_stack_info=False): ...
218
def format(self, record) -> str: ...
219
```
220
221
[Standard Library Integration](./stdlib-integration.md)
222
223
### Context Management
224
225
Thread-safe context binding using contextvars and deprecated thread-local storage, enabling global context that persists across function calls and async boundaries.
226
227
```python { .api }
228
def get_contextvars() -> dict[str, Any]: ...
229
def bind_contextvars(**kw) -> Mapping[str, contextvars.Token[Any]]: ...
230
def clear_contextvars() -> None: ...
231
def unbind_contextvars(*keys) -> None: ...
232
233
def bound_contextvars(**kw) -> Generator[None, None, None]: ...
234
def merge_contextvars(logger, method_name, event_dict) -> EventDict: ...
235
```
236
237
[Context Management](./context-management.md)
238
239
### Testing Utilities
240
241
Comprehensive testing support including log capture, return loggers, and utilities for asserting on structured log output in test suites.
242
243
```python { .api }
244
class ReturnLogger:
245
def msg(self, *args, **kw): ...
246
247
class CapturingLogger:
248
calls: list[CapturedCall]
249
250
def capture_logs() -> Generator[list[EventDict], None, None]: ...
251
252
class LogCapture:
253
entries: list[EventDict]
254
def __call__(self, logger, method_name, event_dict) -> NoReturn: ...
255
```
256
257
[Testing](./testing.md)
258
259
### Output Loggers
260
261
Direct file output loggers that bypass standard logging infrastructure for high-performance logging scenarios and simple output requirements.
262
263
```python { .api }
264
class PrintLogger:
265
def __init__(self, file=None): ...
266
def msg(self, message: str) -> None: ...
267
268
class WriteLogger:
269
def __init__(self, file=None): ...
270
def msg(self, message: str) -> None: ...
271
272
class BytesLogger:
273
def __init__(self, file=None): ...
274
def msg(self, message: bytes) -> None: ...
275
276
class PrintLoggerFactory:
277
def __init__(self, file=None): ...
278
def __call__(self, *args) -> PrintLogger: ...
279
280
class WriteLoggerFactory:
281
def __init__(self, file=None): ...
282
def __call__(self, *args) -> WriteLogger: ...
283
284
class BytesLoggerFactory:
285
def __init__(self, file=None): ...
286
def __call__(self, *args) -> BytesLogger: ...
287
```
288
289
[Output Loggers](./output-loggers.md)
290
291
### Exception and Traceback Handling
292
293
Advanced exception processing including structured traceback extraction, rich formatting, and JSON-serializable exception representations.
294
295
```python { .api }
296
class ExceptionDictTransformer:
297
def __init__(
298
self,
299
show_locals=True,
300
locals_max_length=10,
301
locals_max_string=80,
302
locals_hide_dunder=True,
303
locals_hide_sunder=False,
304
suppress=(),
305
max_frames=50,
306
use_rich=True
307
): ...
308
def __call__(self, exc_info) -> list[dict[str, Any]]: ...
309
310
def extract(exc_type, exc_value, traceback, **kwargs) -> Trace: ...
311
```
312
313
[Exception Handling](./exception-handling.md)
314
315
## Core Types
316
317
```python { .api }
318
# Type aliases
319
WrappedLogger = Any # Logger wrapped by bound logger
320
Context = Union[Dict[str, Any], Dict[Any, Any]] # Dict-like context carrier
321
EventDict = MutableMapping[str, Any] # Event dictionary for processors
322
ProcessorReturnValue = Union[Mapping[str, Any], str, bytes, bytearray, Tuple[Any, ...]]
323
Processor = Callable[[WrappedLogger, str, EventDict], ProcessorReturnValue]
324
ExcInfo = Tuple[Type[BaseException], BaseException, Optional[TracebackType]]
325
ExceptionRenderer = Callable[[TextIO, ExcInfo], None]
326
327
# Additional types
328
Self = TypeVar('Self', bound='BoundLoggerBase') # For bound logger methods
329
NoReturn = typing.NoReturn # For functions that don't return
330
CapturedCall = NamedTuple # Testing utility type with fields: method_name, args, kwargs
331
332
# Core exception
333
class DropEvent(BaseException):
334
"""Exception to drop log events silently."""
335
```