1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
|
.. _api:
API Reference
=============
.. note::
The examples here use a very simplified configuration using the minimalist `structlog.processors.KeyValueRenderer` for brevity and to enable doctests.
The output is going to be different (nicer!) with the default configuration.
.. testsetup:: *
import structlog
structlog.configure(
processors=[structlog.processors.KeyValueRenderer()],
)
.. testcleanup:: *
import structlog
structlog.reset_defaults()
.. module:: structlog
`structlog` Package
-------------------
.. autofunction:: get_logger
.. autofunction:: getLogger
.. autofunction:: wrap_logger
.. autofunction:: configure
.. autofunction:: configure_once
.. autofunction:: reset_defaults
.. autofunction:: is_configured
.. autofunction:: get_config
.. autoclass:: BoundLogger
:members: new, bind, unbind
.. autofunction:: make_filtering_bound_logger
.. autofunction:: get_context
.. autoclass:: PrintLogger
:members: msg, err, debug, info, warning, error, critical, log, failure, fatal
.. autoclass:: PrintLoggerFactory
.. autoclass:: WriteLogger
:members: msg, err, debug, info, warning, error, critical, log, failure, fatal
.. autoclass:: WriteLoggerFactory
.. autoclass:: BytesLogger
:members: msg, err, debug, info, warning, error, critical, log, failure, fatal
.. autoclass:: BytesLoggerFactory
.. autoexception:: DropEvent
.. autoclass:: BoundLoggerBase
:members: new, bind, unbind, try_unbind, _logger, _process_event, _proxy_to_logger
`structlog.dev` Module
----------------------
.. automodule:: structlog.dev
.. autoclass:: ConsoleRenderer
:members: get_default_level_styles
.. autoclass:: Column
.. autoclass:: ColumnFormatter(typing.Protocol)
:members: __call__
.. autoclass:: KeyValueColumnFormatter
.. autoclass:: LogLevelColumnFormatter
.. autofunction:: plain_traceback
.. autoclass:: RichTracebackFormatter
.. autofunction:: rich_traceback
.. autofunction:: better_traceback
.. autofunction:: set_exc_info
`structlog.testing` Module
--------------------------
.. automodule:: structlog.testing
.. autofunction:: capture_logs
.. autoclass:: LogCapture
.. autoclass:: CapturingLogger
>>> 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'})]
.. autoclass:: CapturingLoggerFactory
.. autoclass:: CapturedCall
.. autoclass:: ReturnLogger
:members: msg, err, debug, info, warning, error, critical, log, failure, fatal
.. autoclass:: ReturnLoggerFactory
`structlog.contextvars` Module
------------------------------
.. automodule:: structlog.contextvars
.. autofunction:: bind_contextvars
.. autofunction:: bound_contextvars
.. autofunction:: get_contextvars
.. autofunction:: get_merged_contextvars
.. autofunction:: merge_contextvars
.. autofunction:: clear_contextvars
.. autofunction:: unbind_contextvars
.. autofunction:: reset_contextvars
`structlog.threadlocal` Module
------------------------------
.. automodule:: structlog.threadlocal
:noindex:
.. _procs:
`structlog.processors` Module
-----------------------------
.. automodule:: structlog.processors
.. autoclass:: JSONRenderer
.. doctest::
>>> from structlog.processors import JSONRenderer
>>> JSONRenderer(sort_keys=True)(None, "", {"a": 42, "b": [1, 2, 3]})
'{"a": 42, "b": [1, 2, 3]}'
Bound objects are attempted to be serialize using a ``__structlog__`` method.
If none is defined, ``repr()`` is used:
.. doctest::
>>> 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()})
'{"c1": ["C1!"], "c2": "No __structlog__, so this is used."}'
Please note that additionally to strings, you can also return any type the standard library JSON module knows about -- like in this example a list.
If you choose to pass a *default* parameter as part of *dumps_kw*, support for ``__structlog__`` is disabled.
That can be useful with more elegant serialization methods like `functools.singledispatch`: `Better Python Object Serialization <https://hynek.me/articles/serialization/>`_.
It can also be helpful if you are using *orjson* and want to rely on it to serialize `datetime.datetime` and other objects natively.
.. tip::
If you use this processor, you may also wish to add structured tracebacks for exceptions.
You can do this by adding the :class:`~structlog.processors.dict_tracebacks` to your list of processors:
.. doctest::
>>> 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": "<doctest default[3]>", "lineno": 2, "name": "<module>", "locals": {..., "var": "'spam'"}}], "is_group": false, "exceptions": []}]}
.. autoclass:: KeyValueRenderer
.. doctest::
>>> from structlog.processors import KeyValueRenderer
>>> KeyValueRenderer(sort_keys=True)(None, "", {"a": 42, "b": [1, 2, 3]})
'a=42 b=[1, 2, 3]'
>>> KeyValueRenderer(key_order=["b", "a"])(None, "",
... {"a": 42, "b": [1, 2, 3]})
'b=[1, 2, 3] a=42'
.. autoclass:: LogfmtRenderer
.. doctest::
>>> 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'
.. autoclass:: EventRenamer
.. autofunction:: add_log_level
.. autoclass:: UnicodeDecoder
.. autoclass:: UnicodeEncoder
.. autoclass:: ExceptionRenderer
.. autofunction:: format_exc_info
.. doctest::
>>> 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):...
.. autofunction:: dict_tracebacks
.. doctest::
>>> from structlog.processors import dict_tracebacks
>>> try:
... raise ValueError("onoes")
... except ValueError:
... dict_tracebacks(None, "", {"exc_info": True}) # doctest: +ELLIPSIS
{'exception': [{'exc_type': 'ValueError', 'exc_value': 'onoes', ..., 'frames': [{'filename': ...
.. autoclass:: StackInfoRenderer
.. autoclass:: ExceptionPrettyPrinter
.. autoclass:: TimeStamper
.. doctest::
>>> from structlog.processors import TimeStamper
>>> TimeStamper()(None, "", {}) # doctest: +SKIP
{'timestamp': 1378994017}
>>> TimeStamper(fmt="iso")(None, "", {}) # doctest: +SKIP
{'timestamp': '2013-09-12T13:54:26.996778Z'}
>>> TimeStamper(fmt="%Y", key="year")(None, "", {}) # doctest: +SKIP
{'year': '2013'}
.. autoclass:: MaybeTimeStamper
.. doctest::
>>> from structlog.processors import MaybeTimeStamper
>>> MaybeTimeStamper()(None, "", {}) # doctest: +SKIP
{'timestamp': 1690036074.494428}
>>> MaybeTimeStamper()(None, "", {"timestamp": 42})
{'timestamp': 42}
.. autoclass:: CallsiteParameter
:members:
.. autoclass:: CallsiteParameterAdder
`structlog.stdlib` Module
-------------------------
.. automodule:: structlog.stdlib
.. autofunction:: recreate_defaults
.. autofunction:: get_logger
.. autoclass:: BoundLogger
:members: bind, unbind, try_unbind, new, debug, info, warning, warn, error, critical, exception, log, adebug, ainfo, awarning, aerror, acritical, aexception, alog
.. autoclass:: AsyncBoundLogger
:members: sync_bl
.. autoclass:: LoggerFactory
:members: __call__
.. autofunction:: render_to_log_args_and_kwargs
.. autofunction:: render_to_log_kwargs
.. autofunction:: filter_by_level
.. autofunction:: add_log_level
.. autofunction:: add_log_level_number
.. autofunction:: add_logger_name
.. autoclass:: ExtraAdder
.. autoclass:: PositionalArgumentsFormatter
.. autoclass:: ProcessorFormatter
:members: wrap_for_formatter, remove_processors_meta
`structlog.tracebacks` Module
-----------------------------
.. automodule:: structlog.tracebacks
.. autofunction:: extract
.. autoclass:: ExceptionDictTransformer
.. autoclass:: Trace
.. autoclass:: Stack
.. autoclass:: Frame
.. autoclass:: SyntaxError_
`structlog.typing` Module
-------------------------
.. automodule:: structlog.typing
.. autoclass:: BindableLogger
Additionally to the methods listed below, bound loggers **must** have a ``__init__`` method with the following signature:
.. method:: __init__(self, wrapped_logger: WrappedLogger, processors: Iterable[Processor], context: Context) -> None
:noindex:
Unfortunately it's impossible to define initializers using :pep:`544` Protocols.
They currently also have to carry a `Context` as a ``_context`` attribute.
.. note::
Currently Sphinx has no support for Protocols, so please click ``[source]`` for this entry to see the full definition.
.. autoclass:: FilteringBoundLogger
.. note::
Currently Sphinx has no support for Protocols, so please click ``[source]`` for this entry to see the full definition.
.. autoclass:: ExceptionTransformer
.. note::
Currently Sphinx has no support for Protocols, so please click ``[source]`` for this entry to see the full definition.
.. autodata:: EventDict
.. autodata:: WrappedLogger
.. autodata:: Processor
.. autodata:: Context
.. autodata:: ExcInfo
.. autodata:: ExceptionRenderer
`structlog.twisted` Module
--------------------------
.. automodule:: structlog.twisted
.. autoclass:: BoundLogger
:members: bind, unbind, new, msg, err
.. autoclass:: LoggerFactory
:members: __call__
.. autoclass:: EventAdapter
.. autoclass:: JSONRenderer
.. autofunction:: plainJSONStdOutLogger
.. autofunction:: JSONLogObserverWrapper
.. autoclass:: PlainFileLogObserver
|