0
# Logger Creation and Wrapping
1
2
Core functions for creating and wrapping loggers in structlog. These functions provide the main entry points for getting configured logger instances and integrating existing loggers with structlog's processor pipeline.
3
4
## Capabilities
5
6
### Logger Creation
7
8
Get logger instances according to the current structlog configuration.
9
10
```python { .api }
11
def get_logger(*args, **initial_values) -> Any:
12
"""
13
Get a logger according to current configuration.
14
15
Args:
16
*args: Positional arguments passed to logger factory
17
**initial_values: Initial context values to bind to the logger
18
19
Returns:
20
Logger instance wrapped according to current configuration
21
"""
22
23
def getLogger(*args, **initial_values) -> Any:
24
"""
25
Alias for get_logger() using CamelCase naming convention.
26
27
Args:
28
*args: Positional arguments passed to logger factory
29
**initial_values: Initial context values to bind to the logger
30
31
Returns:
32
Logger instance wrapped according to current configuration
33
"""
34
```
35
36
### Logger Wrapping
37
38
Wrap existing logger instances with structlog functionality, allowing integration with any logging system.
39
40
```python { .api }
41
def wrap_logger(
42
logger,
43
processors=None,
44
wrapper_class=None,
45
context_class=None,
46
cache_logger_on_first_use=None,
47
logger_factory_args=None,
48
**initial_values
49
) -> Any:
50
"""
51
Wrap an existing logger with structlog functionality.
52
53
Args:
54
logger: Logger instance to wrap
55
processors (list, optional): Processor chain (defaults to global config)
56
wrapper_class (type, optional): Wrapper class (defaults to global config)
57
context_class (type, optional): Context class (defaults to global config)
58
cache_logger_on_first_use (bool, optional): Caching behavior (defaults to global config)
59
logger_factory_args (tuple, optional): Arguments for logger factory
60
**initial_values: Initial context values to bind
61
62
Returns:
63
Wrapped logger instance with structlog functionality
64
"""
65
```
66
67
## Usage Examples
68
69
### Basic Logger Creation
70
71
```python
72
import structlog
73
74
# Configure structlog first
75
structlog.configure(
76
processors=[structlog.processors.JSONRenderer()],
77
wrapper_class=structlog.stdlib.BoundLogger,
78
logger_factory=structlog.stdlib.LoggerFactory(),
79
)
80
81
# Get a logger
82
logger = structlog.get_logger()
83
logger.info("Application started")
84
85
# Get a logger with initial context
86
logger = structlog.get_logger(user_id=123, session="abc")
87
logger.info("User action", action="login")
88
```
89
90
### Named Loggers
91
92
```python
93
import structlog
94
95
# Get named logger (for stdlib integration)
96
logger = structlog.get_logger("myapp.auth")
97
logger.info("Authentication module loaded")
98
99
# Alternative spelling
100
logger = structlog.getLogger("myapp.database")
101
logger.info("Database connection established")
102
```
103
104
### Wrapping Existing Loggers
105
106
```python
107
import logging
108
import structlog
109
110
# Create a standard library logger
111
stdlib_logger = logging.getLogger("myapp")
112
113
# Wrap it with structlog
114
logger = structlog.wrap_logger(
115
stdlib_logger,
116
processors=[
117
structlog.processors.TimeStamper(),
118
structlog.processors.add_log_level,
119
structlog.processors.JSONRenderer()
120
]
121
)
122
123
logger.info("Wrapped logger", component="auth")
124
```
125
126
### Custom Logger Wrapping
127
128
```python
129
import structlog
130
131
class CustomLogger:
132
def __init__(self, name):
133
self.name = name
134
135
def log(self, level, message):
136
print(f"[{level}] {self.name}: {message}")
137
138
# Wrap custom logger
139
custom = CustomLogger("myapp")
140
logger = structlog.wrap_logger(
141
custom,
142
processors=[structlog.processors.JSONRenderer()],
143
wrapper_class=structlog.BoundLogger
144
)
145
146
logger.info("Custom logger wrapped", service="api")
147
```
148
149
### Per-Logger Configuration
150
151
```python
152
import structlog
153
154
# Global configuration
155
structlog.configure(
156
processors=[structlog.processors.KeyValueRenderer()],
157
wrapper_class=structlog.BoundLogger,
158
)
159
160
# Override configuration for specific logger
161
import logging
162
stdlib_logger = logging.getLogger("special")
163
164
special_logger = structlog.wrap_logger(
165
stdlib_logger,
166
processors=[
167
structlog.processors.TimeStamper(),
168
structlog.processors.JSONRenderer()
169
],
170
wrapper_class=structlog.stdlib.BoundLogger
171
)
172
173
# Regular logger uses global config
174
regular_logger = structlog.get_logger()
175
176
regular_logger.info("Using global config") # KeyValue output
177
special_logger.info("Using custom config") # JSON output
178
```
179
180
### Logger with Factory Arguments
181
182
```python
183
import structlog
184
185
def custom_logger_factory(name=None):
186
import logging
187
logger = logging.getLogger(name or "default")
188
logger.setLevel(logging.DEBUG)
189
return logger
190
191
# Configure with custom factory
192
structlog.configure(
193
logger_factory=custom_logger_factory,
194
wrapper_class=structlog.stdlib.BoundLogger,
195
)
196
197
# Create logger with factory arguments
198
logger = structlog.get_logger("myapp.service")
199
logger.debug("Debug message") # Will be shown due to DEBUG level
200
```
201
202
### Context Binding at Creation
203
204
```python
205
import structlog
206
207
# Configure structlog
208
structlog.configure(
209
processors=[structlog.processors.JSONRenderer()],
210
wrapper_class=structlog.BoundLogger,
211
)
212
213
# Create logger with initial context
214
request_logger = structlog.get_logger(
215
request_id="req-123",
216
user_id=456,
217
endpoint="/api/users"
218
)
219
220
# All log calls will include the initial context
221
request_logger.info("Request started")
222
request_logger.info("Processing data", records_count=10)
223
request_logger.info("Request completed", status_code=200)
224
```