API Reference

Contents

API Reference#

Note

The examples here use a very simplified configuration using the minimaliststructlog.processors.KeyValueRenderer for brevity and to enable doctests.The output is going to be different (nicer!) with the default configuration.

structlog Package#

structlog.get_logger(*args,**initial_values)[source]#

Convenience function that returns a logger according to configuration.

>>>fromstructlogimportget_logger>>>log=get_logger(y=23)>>>log.info("hello",x=42)y=23 x=42 event='hello'
Parameters:
  • args (Any) –Optional positional arguments that are passed unmodified to thelogger factory. Therefore it depends on the factory what theymean.

  • initial_values (Any) – Values that are used to pre-populate your contexts.

Returns:

A proxy that creates a correctly configured bound logger whennecessary. The type of that bound logger depends on your configurationand isstructlog.BoundLogger by default.

Return type:

Any

SeeConfiguration for details.

If you prefer CamelCase, there’s an alias for your reading pleasure:structlog.getLogger.

Added in version 0.4.0:args

structlog.getLogger(*args,**initial_values)#

CamelCase alias forstructlog.get_logger.

This function is supposed to be in every source file – we don’t want it tostick out like a sore thumb in frameworks like Twisted or Zope.

structlog.wrap_logger(logger,processors=None,wrapper_class=None,context_class=None,cache_logger_on_first_use=None,logger_factory_args=None,**initial_values)[source]#

Create a new bound logger for an arbitrarylogger.

Default values forprocessors,wrapper_class, andcontext_class canbe set usingconfigure.

If you set an attribute here,configure calls haveno effect for therespective attribute.

In other words: selective overwriting of the defaults while keeping someis possible.

Parameters:
  • initial_values (Any) – Values that are used to pre-populate your contexts.

  • logger_factory_args (Iterable[Any]|None) – Values that are passed unmodified as*logger_factory_args tothe logger factory if notNone.

Returns:

A proxy that creates a correctly configured bound logger whennecessary.

Return type:

Any

Seeconfigure for the meaning of the rest of the arguments.

Added in version 0.4.0:logger_factory_args

structlog.configure(processors=None,wrapper_class=None,context_class=None,logger_factory=None,cache_logger_on_first_use=None)[source]#

Configures theglobal defaults.

They are used ifwrap_logger orget_logger are called withoutarguments.

Can be called several times, keeping an argument atNone leaves itunchanged from the current setting.

After calling for the first time,is_configured starts returningTrue.

Usereset_defaults to undo your changes.

Parameters:

Added in version 0.3.0:cache_logger_on_first_use

structlog.configure_once(processors=None,wrapper_class=None,context_class=None,logger_factory=None,cache_logger_on_first_use=None)[source]#

Configures if structlog isn’t configured yet.

It doesnot matter whether it was configured usingconfigure orconfigure_once before.

Raises:

RuntimeWarning – if repeated configuration is attempted.

structlog.reset_defaults()[source]#

Resets global default values to builtin defaults.

is_configured starts returningFalse afterwards.

structlog.is_configured()[source]#

Return whetherstructlog has been configured.

IfFalse,structlog is running with builtin defaults.

structlog.get_config()[source]#

Get a dictionary with the current configuration.

Note

Changes to the returned dictionary donot affectstructlog.

classstructlog.BoundLogger(logger,processors,context)[source]#

A generic BoundLogger that can wrap anything.

Every unknown method will be passed to the wrappedlogger. If that’s toomuch magic for you, trystructlog.stdlib.BoundLogger orstructlog.twisted.BoundLogger which also take advantage of knowing thewrapped class which generally results in better performance.

Not intended to be instantiated by yourself. Seewrap_logger() andget_logger().

bind(**new_values)#

Return a new logger withnew_values added to the existing ones.

new(**new_values)#

Clear context and bindsnew_values usingbind.

Only necessary with dict implementations that keep global state likethose wrapped bystructlog.threadlocal.wrap_dict when threadsare reused.

unbind(*keys)#

Return a new logger withkeys removed from the context.

Raises:

KeyError – If the key is not part of the context.

structlog.make_filtering_bound_logger(min_level)[source]#

Create a newFilteringBoundLogger that only logsmin_level or higher.

The logger is optimized such that log levels belowmin_level only consistof areturnNone.

All familiar log methods are present, with async variants of each that areprefixed by ana. Therefore, the async version oflog.info("hello")isawaitlog.ainfo("hello").

Additionally it has alog(self,level:int,**kw:Any) method to mirrorlogging.Logger.log andstructlog.stdlib.BoundLogger.log.

Compared to usingstructlog’s standard library integration and thestructlog.stdlib.filter_by_level processor:

  • It’s faster because once the logger is built at program start; it’s astatic class.

  • For the same reason you can’t change the log level once configured. Usethe dynamic approach ofStandard Library Logging instead, if you need thisfeature.

  • Youcan have (much) more fine-grained filtering bywriting asimple processor.

Parameters:

min_level (int |str) –

The log level as an integer. You can use the constants fromlogging likelogging.INFO or pass the values directly. Seethis table from the logging docs forpossible values.

If you pass a string, it must be one of:critical,error,warning,info,debug,notset (upper/lower casedoesn’t matter).

Added in version 20.2.0.

Changed in version 21.1.0:The returned loggers are now pickleable.

Added in version 20.1.0:Thelog() method.

Added in version 22.2.0:Async variantsalog(),adebug(),ainfo(), and so forth.

Changed in version 25.1.0:min_level can now be a string.

structlog.get_context(bound_logger)[source]#

Returnbound_logger’s context.

The type ofbound_logger and the type returned depend on yourconfiguration.

Parameters:

bound_logger (BindableLogger) – The bound logger whose context you want.

Returns:

Theactual context frombound_logger. It isnot copied first.

Return type:

Dict[str,Any] |Dict[Any,Any]

Added in version 20.2.0.

classstructlog.PrintLogger(file=None)[source]#

Print events into a file.

Parameters:

file (TextIO |None) – File to print to. (default:sys.stdout)

>>>fromstructlogimportPrintLogger>>>PrintLogger().info("hello")hello

Useful if you followcurrent logging best practices.

Also very useful for testing and examples sincelogging is finicky indoctests.

Changed in version 22.1.0:The implementation has been switched to useprint for bettermonkeypatchability.

critical(message)#

Printmessage.

debug(message)#

Printmessage.

err(message)#

Printmessage.

error(message)#

Printmessage.

failure(message)#

Printmessage.

fatal(message)#

Printmessage.

info(message)#

Printmessage.

log(message)#

Printmessage.

msg(message)[source]#

Printmessage.

warning(message)#

Printmessage.

classstructlog.PrintLoggerFactory(file=None)[source]#

ProducePrintLoggers.

To be used withstructlog.configure‘slogger_factory.

Parameters:

file (TextIO |None) – File to print to. (default:sys.stdout)

Positional arguments are silently ignored.

Added in version 0.4.0.

classstructlog.WriteLogger(file=None)[source]#

Write events into a file.

Parameters:

file (TextIO |None) – File to print to. (default:sys.stdout)

>>>fromstructlogimportWriteLogger>>>WriteLogger().info("hello")hello

Useful if you followcurrent logging best practices.

Also very useful for testing and examples sincelogging is finicky indoctests.

A little faster and a little less versatile thanstructlog.PrintLogger.

Added in version 22.1.0.

critical(message)#

Write and flushmessage.

debug(message)#

Write and flushmessage.

err(message)#

Write and flushmessage.

error(message)#

Write and flushmessage.

failure(message)#

Write and flushmessage.

fatal(message)#

Write and flushmessage.

info(message)#

Write and flushmessage.

log(message)#

Write and flushmessage.

msg(message)[source]#

Write and flushmessage.

warning(message)#

Write and flushmessage.

classstructlog.WriteLoggerFactory(file=None)[source]#

ProduceWriteLoggers.

To be used withstructlog.configure‘slogger_factory.

Parameters:

file (TextIO |None) – File to print to. (default:sys.stdout)

Positional arguments are silently ignored.

Added in version 22.1.0.

classstructlog.BytesLogger(file=None)[source]#

Writes bytes into a file.

Parameters:

file (BinaryIO |None) – File to print to. (default:sys.stdout.buffer)

Useful if you followcurrent logging best practices together with a formatter that returns bytes(e.g.orjson).

Added in version 20.2.0.

critical(message)#

Writemessage.

debug(message)#

Writemessage.

err(message)#

Writemessage.

error(message)#

Writemessage.

failure(message)#

Writemessage.

fatal(message)#

Writemessage.

info(message)#

Writemessage.

log(message)#

Writemessage.

msg(message)[source]#

Writemessage.

warning(message)#

Writemessage.

classstructlog.BytesLoggerFactory(file=None)[source]#

ProduceBytesLoggers.

To be used withstructlog.configure‘slogger_factory.

Parameters:

file (BinaryIO |None) – File to print to. (default:sys.stdout.buffer)

Positional arguments are silently ignored.

Added in version 20.2.0.

exceptionstructlog.DropEvent[source]#

If raised by an processor, the event gets silently dropped.

Derives from BaseException because it’s technically not an error.

classstructlog.BoundLoggerBase(logger,processors,context)[source]#

Immutable context carrier.

Doesn’t do any actual logging; examples for useful subclasses are:

See alsoCustom wrappers.

_logger:Any#

Wrapped logger.

Note

Despite underscore availableread-only to custom wrapper classes.

See alsoCustom wrappers.

_process_event(method_name,event,event_kw)[source]#

Combines creates anevent_dict and runs the chain.

Call it to combine yourevent andcontext into an event_dict andprocess using the processor chain.

Parameters:
  • method_name (str) – The name of the logger method. Is passed into the processors.

  • event (str |None) – The event – usually the first positional argument to a logger.

  • event_kw (dict[str,Any]) – Additional event keywords. For example if someone callslog.info("foo",bar=42),event would to be"foo" andevent_kw{"bar":42}.

Raises:
  • structlog.DropEvent – if log entry should be dropped.

  • ValueError – if the final processor doesn’t return a str, bytes, bytearray, tuple, or a dict.

Returns:

tuple of(*args,**kw)

Return type:

tuple[Sequence[Any],Mapping[str,Any]]

Note

Despite underscore available to custom wrapper classes.

See alsoCustom wrappers.

Changed in version 14.0.0:Allow final processor to return adict.

Changed in version 20.2.0:Allow final processor to returnbytes.

Changed in version 21.2.0:Allow final processor to return abytearray.

_proxy_to_logger(method_name,event=None,**event_kw)[source]#

Run processor chain on event & callmethod_name on wrapped logger.

DRY convenience method that runs_process_event(), takes care ofhandlingstructlog.DropEvent, and finally callsmethod_name on_logger with the result.

Parameters:
  • method_name (str) – The name of the method that’s going to get called. Technicallyit should be identical to the method the user called because italso get passed into processors.

  • event (str |None) – The event – usually the first positional argument to a logger.

  • event_kw (Any) – Additional event keywords. For example if someone callslog.info("foo",bar=42),event would to be"foo" andevent_kw{"bar":42}.

Note

Despite underscore available to custom wrapper classes.

See alsoCustom wrappers.

bind(**new_values)[source]#

Return a new logger withnew_values added to the existing ones.

new(**new_values)[source]#

Clear context and bindsnew_values usingbind.

Only necessary with dict implementations that keep global state likethose wrapped bystructlog.threadlocal.wrap_dict when threadsare reused.

try_unbind(*keys)[source]#

Likeunbind(), but best effort: missing keys are ignored.

Added in version 18.2.0.

unbind(*keys)[source]#

Return a new logger withkeys removed from the context.

Raises:

KeyError – If the key is not part of the context.

structlog.dev Module#

Helpers that make development withstructlog more pleasant.

See also the narrative documentation inConsole Output.

classstructlog.dev.ConsoleRenderer(pad_event_to=30,colors=True,force_colors=False,repr_native_str=False,level_styles=None,exception_formatter=<functionplain_traceback>,sort_keys=True,event_key='event',timestamp_key='timestamp',columns=None,pad_level=True,pad_event=None)[source]#

Renderevent_dict nicely aligned, possibly in colors, and ordered.

Ifevent_dict contains a true-ishexc_info key, it will be renderedafter the log line. IfRich orbetter-exceptions are present, in colorsand with extra context.

Tip

SinceConsoleRenderer is mainly a development helper, it is lessstrict about immutability than the rest ofstructlog for betterergonomics. Notably, the currently active instance can be obtained bycallingConsoleRenderer.get_active() and it offers properties toconfigure its behavior after instantiation.

Parameters:
  • columns (list[Column]|None) –

    A list ofColumn objects defining both the order and format ofthe key-value pairs in the output. If passed, most other argumentsbecome meaningless.

    Must contain a column withkey='' that defines the defaultformatter.

  • pad_event_to (int) – Pad the event to this many characters. Ignored ifcolumns arepassed.

  • colors (bool) – Use colors for a nicer output.True by default. On Windows onlyifColorama is installed. Ignored ifcolumns are passed.

  • force_colors (bool) – Force colors even for non-tty destinations. Use this option if yourlogs are stored in a file that is meant to be streamed to theconsole. Only meaningful on Windows. Ignored ifcolumns arepassed.

  • repr_native_str (bool) – WhenTrue,repr is also applied tostrs. Theeventkey isneverrepr -ed. Ignored ifcolumns are passed.

  • level_styles (dict[str,str]|None) – When present, use these styles for colors. This must be a dict fromlevel names (strings) to terminal sequences (for example, Colorama)styles. The default can be obtained by callingConsoleRenderer.get_default_level_styles. Ignored whencolumnsare passed.

  • exception_formatter (ExceptionRenderer) – A callable to renderexc_infos. IfRich orbetter-exceptionsare installed, they are used for pretty-printing by default (richtaking precedence). You can also manually set it toplain_traceback,better_traceback, an instance ofRichTracebackFormatter likerich_traceback, or implement yourown.

  • sort_keys (bool) – Whether to sort keys when formatting.True by default. Ignored ifcolumns are passed.

  • event_key (str) – The key to look for the main log message. Needed when you rename ite.g. usingstructlog.processors.EventRenamer. Ignored ifcolumns are passed.

  • timestamp_key (str) – The key to look for timestamp of the log message. Needed when yourename it e.g. usingstructlog.processors.EventRenamer. Ignoredifcolumns are passed.

  • pad_level (bool) – Whether to pad log level with blanks to the longest amongst alllevel label.

Requires theColorama package ifcolors isTrueon Windows.

Raises:

ValueError – If there’s not exactly one default column formatter.

Added in version 16.0.0.

Added in version 16.1.0:colors

Added in version 17.1.0:repr_native_str

Added in version 18.1.0:force_colors

Added in version 18.1.0:level_styles

Changed in version 19.2.0:Colorama now initializes lazily to avoid unwanted initializations asConsoleRenderer is used by default.

Changed in version 19.2.0:Can be pickled now.

Changed in version 20.1.0:Colorama does not initialize lazily on Windows anymore because it breaksrendering.

Changed in version 21.1.0:It is additionally possible to set the logger name using thelogger_name key in theevent_dict.

Added in version 21.2.0:exception_formatter

Changed in version 21.2.0:ConsoleRenderer now handles theexc_info event dict key itself. Donot use thestructlog.processors.format_exc_info processortogether withConsoleRenderer anymore! It will keep working, but youcan’t have customize exception formatting and a warning will be raisedif you ask for it.

Changed in version 21.2.0:The colors keyword now defaults to True on non-Windows systems, andeither True or False in Windows depending on whether Colorama isinstalled.

Added in version 21.3.0:sort_keys

Added in version 22.1.0:event_key

Added in version 23.2.0:timestamp_key

Added in version 23.3.0:columns

Added in version 24.2.0:pad_level

propertycolors:bool#

Whether to use colorful output styles.

Setting this will update the renderer’s styles immediately and resetlevel styles to the defaults according to the new color setting – evenif the color value is the same.

Added in version 25.5.0.

propertycolumns:list[Column]#

The columns configuration for this console renderer.

Warning

Just like with passingcolumns argument, many of the otherarguments you may have passed are ignored.

Parameters:

value

A list ofColumn objects defining both the order and formatof the key-value pairs in the output.

Must contain a column withkey='' that defines thedefault formatter.

Raises:

ValueError – If there’s not exactly one default column formatter.

Added in version 25.5.0.

propertyevent_key:str#

The key to look for the main log message.

Setting this will rebuild columns to reflect the change.

Added in version 25.5.0.

propertyexception_formatter:Callable[[TextIO,Tuple[Type[BaseException],BaseException,TracebackType|None]],None]#

The exception formatter used by this console renderer.

Added in version 25.5.0.

propertyforce_colors:bool#

Force colorful output even in non-interactive environments.

Setting this will update the renderer’s styles immediately and resetlevel styles to the defaults according to the current color setting –even if the value is the same.

Added in version 25.5.0.

classmethodget_active()[source]#

Ifstructlog is configured to useConsoleRenderer, it’s returned.

It does not have to be the last processor.

Raises:

Added in version 25.5.0.

classmethodget_default_column_styles(colors,force_colors=False)[source]#

Configure and return the appropriate styles class for console output.

This method handles the setup of colorful or plain styles, includingproper colorama initialization on Windows systems when colors areenabled.

Parameters:
  • colors (bool) – Whether to use colorful output styles.

  • force_colors (bool) – Force colorful output even in non-interactive environments.Only relevant on Windows with colorama.

Returns:

The configured styles.

Raises:

SystemError – On Windows when colors=True but colorama is not installed.

Return type:

ColumnStyles

Added in version 25.5.0.

staticget_default_level_styles(colors=True)[source]#

Get the default styles for log levels

This is intended to be used withConsoleRenderer’slevel_stylesparameter. For example, if you are adding custom levels in yourhome-grownadd_log_level() you could do:

my_styles=ConsoleRenderer.get_default_level_styles()my_styles["EVERYTHING_IS_ON_FIRE"]=my_styles["critical"]renderer=ConsoleRenderer(level_styles=my_styles)
Parameters:

colors (bool) – Whether to use colorful styles. This must match thecolorsparameter toConsoleRenderer. Default:True.

propertylevel_styles:dict[str,str]#

The level styles mapping for this console renderer.

Setting this property will reset to defaults if set to None, otherwiseit applies the provided mapping. In all cases, columns are rebuilt toreflect the change.

Added in version 25.5.0.

propertypad_event_to:int#

The number of characters to pad the event to.

Setting this will rebuild columns to reflect the change.

Added in version 25.5.0.

propertypad_level:bool#

Whether to pad log level with blanks to the longest amongst alllevel labels.

Setting this will rebuild columns to reflect the change.

Added in version 25.5.0.

propertyrepr_native_str:bool#

Whether native strings are passed through repr() in non-event values.

Added in version 25.5.0.

propertysort_keys:bool#

Whether to sort keys when formatting.

Added in version 25.5.0.

propertytimestamp_key:str#

The key to look for the timestamp of the log message.

Setting this will rebuild columns to reflect the change.

Added in version 25.5.0.

classstructlog.dev.ColumnStyles(reset,bright,level_critical,level_exception,level_error,level_warn,level_info,level_debug,level_notset,timestamp,logger_name,kv_key,kv_value)[source]#

Column styles settings for console rendering.

These are console ANSI codes that are printed before the respective fields.This allows for a certain amount of customization if you don’t want toconfigure your columns.

Added in version 25.5.0:It was handled by private structures before.

exceptionstructlog.dev.NoConsoleRendererConfiguredError[source]#

A user asked for the currentstructlog.dev.ConsoleRenderer but none isconfigured.

Added in version 25.5.0.

exceptionstructlog.dev.MultipleConsoleRenderersConfiguredError[source]#

A user asked for the currentstructlog.dev.ConsoleRenderer and more than one is configured.

Added in version 25.5.0.

classstructlog.dev.Column(key,formatter)[source]#

A column defines the way a key-value pair is formatted, and, by it’sposition to thecolumns argument ofConsoleRenderer, the order in whichit is rendered.

Parameters:
  • key (str) – The key for which this column is responsible. Leave empty to defineit as the default formatter.

  • formatter (ColumnFormatter) – The formatter for columns withkey.

Added in version 23.3.0.

classstructlog.dev.ColumnFormatter(typing.Protocol)[source]#

Protocol for column formatters.

SeeKeyValueColumnFormatter andLogLevelColumnFormatter for examples.

Added in version 23.3.0.

__call__(key,value)[source]#

Formatvalue forkey.

This method is responsible for formatting,key, the=, and thevalue. That means that it can use any string instead of the= andit can leave out both thekey or thevalue.

If it returns an empty string, the column is omitted completely.

classstructlog.dev.KeyValueColumnFormatter(key_style,value_style,reset_style,value_repr,width=0,prefix='',postfix='')[source]#

Format a key-value pair.

Parameters:
  • key_style (str |None) – The style to apply to the key. If None, the key is omitted.

  • value_style (str) – The style to apply to the value.

  • reset_style (str) – The style to apply whenever a style is no longer needed.

  • value_repr (Callable[[object],str]) – A callable that returns the string representation of the value.

  • width (int) – The width to pad the value to. If 0, no padding is done.

  • prefix (str) – A string to prepend to the formatted key-value pair. May containstyles.

  • postfix (str) – A string to append to the formatted key-value pair. May containstyles.

Added in version 23.3.0.

classstructlog.dev.LogLevelColumnFormatter(level_styles,reset_style,width=None)[source]#

Format a log level according tolevel_styles.

The width is padded to the longest level name (iflevel_styles is passed– otherwise there’s no way to know the lengths of all levels).

Parameters:
  • level_styles (dict[str,str]|None) – A dictionary of level names to styles that are applied to it. IfNone, the level is formatted as a plain[level].

  • reset_style (str) – What to use to reset the style after the level name. Ignored ififlevel_styles is None.

  • width (int) – The width to pad the level to. If 0, no padding is done.

Added in version 23.3.0.

Added in version 24.2.0:width

structlog.dev.plain_traceback(sio,exc_info)[source]#

“Pretty”-printexc_info tosio using our own plain formatter.

To be passed intoConsoleRenderer’sexception_formatter argument.

Used by default if neither Rich norbetter-exceptions are present.

Added in version 21.2.0.

classstructlog.dev.RichTracebackFormatter(color_system='truecolor',show_locals=True,max_frames=100,theme=None,word_wrap=True,extra_lines=3,width=None,code_width=88,indent_guides=True,locals_max_length=10,locals_max_string=80,locals_hide_dunder=True,locals_hide_sunder=False,suppress=())[source]#

A Rich traceback renderer with the given options.

Pass an instance asConsoleRenderer’sexception_formatter argument.

Seerich.traceback.Traceback for details on the arguments.

Ifwidth isNone, the terminal width is used. If the width can’t bedetermined, fall back to 80.

Added in version 23.2.0.

Changed in version 25.4.0:Defaultwidth isNone to have full width and reflow support.Passing-1 as width is deprecated, useNone instead.word_wrap is now True by default.

Added in version 25.4.0:code_width

structlog.dev.rich_traceback(*args,**kw)[source]#

Pretty-printexc_info tosio using the Rich package.

To be passed intoConsoleRenderer’sexception_formatter argument.

This is aRichTracebackFormatter with default arguments and used by defaultif Rich is installed.

Added in version 21.2.0.

structlog.dev.better_traceback(sio,exc_info)[source]#

Pretty-printexc_info tosio using thebetter-exceptions package.

To be passed intoConsoleRenderer’sexception_formatter argument.

Used by default ifbetter-exceptions is installed and Rich is absent.

Added in version 21.2.0.

structlog.dev.set_exc_info(logger,method_name,event_dict)[source]#

Setevent_dict["exc_info"]=True ifmethod_name is"exception".

Do nothing if the name is different orexc_info is already set.

Added in version 19.2.0.

structlog.testing Module#

Helpers to test your application’s logging behavior.

Added in version 20.1.0.

SeeTesting.

structlog.testing.capture_logs(processors=())[source]#

Context manager that appends all logging statements to its yielded listwhile it is active. Disables all configured processors for the durationof the context manager.

Attention: this isnot thread-safe!

Parameters:

processors (Iterable[Callable[[Any,str,MutableMapping[str,Any]],Mapping[str,Any]|str |bytes |bytearray |Tuple[Any,...]]]) – Processors to apply before the logs are captured.

Added in version 20.1.0.

Added in version 25.5.0:processors parameter

classstructlog.testing.LogCapture[source]#

Class for capturing log messages in its entries list.Generally you should usestructlog.testing.capture_logs,but you can use this class if you want to capture logs with other patterns.

Variables:

entries (List[structlog.typing.EventDict]) – The captured log entries.

Added in version 20.1.0.

Changed in version 24.3.0:Added mapping from “exception” to “error”Added mapping from “warn” to “warning”

classstructlog.testing.CapturingLogger[source]#

Store the method calls that it’s been called with.

This is nicer thanReturnLogger for unit tests because the bound loggerdoesn’t have to cooperate.

Any method name is supported.

Added in version 20.2.0.

>>>frompprintimportpprint>>>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'})]
classstructlog.testing.CapturingLoggerFactory[source]#

Produce and cacheCapturingLoggers.

Each factory produces and reuses onlyone logger.

You can access it via thelogger attribute.

To be used withstructlog.configure‘slogger_factory.

Positional arguments are silently ignored.

Added in version 20.2.0.

classstructlog.testing.CapturedCall(method_name,args,kwargs)[source]#

A call as captured byCapturingLogger.

Can also be unpacked like a tuple.

Parameters:
  • method_name (str) – The method name that got called.

  • args (tuple[Any,...]) – A tuple of the positional arguments.

  • kwargs (dict[str,Any]) – A dict of the keyword arguments.

Added in version 20.2.0.

classstructlog.testing.ReturnLogger[source]#

Return the arguments that it’s called with.

>>>fromstructlogimportReturnLogger>>>ReturnLogger().info("hello")'hello'>>>ReturnLogger().info("hello",when="again")(('hello',), {'when': 'again'})

Changed in version 0.3.0:Allow for arbitrary arguments and keyword arguments to be passed in.

critical(*args,**kw)#

Return tuple ofargs,kw or justargs[0] if only one arg passed

debug(*args,**kw)#

Return tuple ofargs,kw or justargs[0] if only one arg passed

err(*args,**kw)#

Return tuple ofargs,kw or justargs[0] if only one arg passed

error(*args,**kw)#

Return tuple ofargs,kw or justargs[0] if only one arg passed

failure(*args,**kw)#

Return tuple ofargs,kw or justargs[0] if only one arg passed

fatal(*args,**kw)#

Return tuple ofargs,kw or justargs[0] if only one arg passed

info(*args,**kw)#

Return tuple ofargs,kw or justargs[0] if only one arg passed

log(*args,**kw)#

Return tuple ofargs,kw or justargs[0] if only one arg passed

msg(*args,**kw)[source]#

Return tuple ofargs,kw or justargs[0] if only one arg passed

warning(*args,**kw)#

Return tuple ofargs,kw or justargs[0] if only one arg passed

classstructlog.testing.ReturnLoggerFactory[source]#

Produce and cacheReturnLoggers.

To be used withstructlog.configure‘slogger_factory.

Positional arguments are silently ignored.

Added in version 0.4.0.

structlog.contextvars Module#

Primitives to deal with a concurrency supporting context, as introduced inPython 3.7 ascontextvars.

Added in version 20.1.0.

Changed in version 21.1.0:Reimplemented without using a single dict as context carrier for improvedisolation. Every key-value pair is a separatecontextvars.ContextVar now.

Changed in version 23.3.0:Callsite parameters are now also collected under asyncio.

SeeContext Variables.

structlog.contextvars.bind_contextvars(**kw)[source]#

Put keys and values into the context-local context.

Use this instead ofbind() when you want somecontext to be global (context-local).

Return the mapping ofcontextvars.Tokens resultingfrom setting the backingContextVars.Suitable for passing toreset_contextvars().

Added in version 20.1.0.

Changed in version 21.1.0:Return thecontextvars.Token mappingrather than None. See also the toplevel note.

structlog.contextvars.bound_contextvars(**kw)[source]#

Bindkw to the current context-local context. Unbind or restorekwafterwards. Donot affect other keys.

Can be used as a context manager or decorator.

Added in version 21.4.0.

structlog.contextvars.get_contextvars()[source]#

Return a copy of thestructlog-specific context-local context.

Added in version 21.2.0.

structlog.contextvars.get_merged_contextvars(bound_logger)[source]#

Return a copy of the current context-local context merged with the contextfrombound_logger.

Added in version 21.2.0.

structlog.contextvars.merge_contextvars(logger,method_name,event_dict)[source]#

A processor that merges in a global (context-local) context.

Use this as your first processor instructlog.configure() to ensurecontext-local context is included in all log calls.

Added in version 20.1.0.

Changed in version 21.1.0:See toplevel note.

structlog.contextvars.clear_contextvars()[source]#

Clear the context-local context.

The typical use-case for this function is to invoke it early in request-handling code.

Added in version 20.1.0.

Changed in version 21.1.0:See toplevel note.

structlog.contextvars.unbind_contextvars(*keys)[source]#

Removekeys from the context-local context if they are present.

Use this instead ofunbind() when you want toremove keys from a global (context-local) context.

Added in version 20.1.0.

Changed in version 21.1.0:See toplevel note.

structlog.contextvars.reset_contextvars(**kw)[source]#

Reset contextvars corresponding to the given Tokens.

Added in version 21.1.0.

structlog.threadlocal Module#

Deprecated primitives to keep context global but thread (and greenlet)local.

SeeLegacy Thread-local Context, but please useContext Variables instead.

Deprecated since version 22.1.0.

structlog.processors Module#

Processors useful regardless of the logging framework.

classstructlog.processors.JSONRenderer(serializer=<functiondumps>,**dumps_kw)[source]#

Render theevent_dict usingserializer(event_dict,**dumps_kw).

Parameters:
  • dumps_kw (Any) – Are passed unmodified toserializer. Ifdefault is passed, itwill disable support for__structlog__-based serialization.

  • serializer (Callable[...,str |bytes]) –

    Ajson.dumps()-compatible callable that will be used toformat the string. This can be used to use alternative JSONencoders (default:json.dumps()).

    See also

    Performance for examples.

Added in version 0.2.0:Support for__structlog__ serialization method.

Added in version 15.4.0:serializer parameter.

Added in version 18.2.0:Serializer’sdefault parameter can be overwritten now.

>>>fromstructlog.processorsimportJSONRenderer>>>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:

>>>classC1:...def__structlog__(self):...return["C1!"]...def__repr__(self):...return"__structlog__ took precedence">>>classC2:...def__repr__(self):...return"No __structlog__, so this is used.">>>fromstructlog.processorsimportJSONRenderer>>>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 adefault parameter as part ofdumps_kw, support for__structlog__ is disabled.That can be useful with more elegant serialization methods likefunctools.singledispatch:Better Python Object Serialization.It can also be helpful if you are usingorjson and want to rely on it to serializedatetime.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 thedict_tracebacks to your list of processors:

>>>structlog.configure(...processors=[...structlog.processors.dict_tracebacks,...structlog.processors.JSONRenderer(),...],...)>>>log=structlog.get_logger()>>>var="spam">>>try:...1/0...exceptZeroDivisionError:...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": []}]}
classstructlog.processors.KeyValueRenderer(sort_keys=False,key_order=None,drop_missing=False,repr_native_str=True)[source]#

Renderevent_dict as a list ofKey=repr(Value) pairs.

Parameters:
  • sort_keys (bool) – Whether to sort keys when formatting.

  • key_order (Sequence[str]|None) – List of keys that should be rendered in this exact order. Missingkeys will be rendered asNone, extra keys depending onsort_keys and the dict class.

  • drop_missing (bool) – WhenTrue, extra keys inkey_order will be dropped ratherthan rendered asNone.

  • repr_native_str (bool) – WhenTrue,repr() is also applied to native strings.

Added in version 0.2.0:key_order

Added in version 16.1.0:drop_missing

Added in version 17.1.0:repr_native_str

>>>fromstructlog.processorsimportKeyValueRenderer>>>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'
classstructlog.processors.LogfmtRenderer(sort_keys=False,key_order=None,drop_missing=False,bool_as_flag=True)[source]#

Renderevent_dict using thelogfmt format.

Parameters:
  • sort_keys (bool) – Whether to sort keys when formatting.

  • key_order (Sequence[str]|None) – List of keys that should be rendered in this exact order. Missingkeys are rendered with empty values, extra keys depending onsort_keys and the dict class.

  • drop_missing (bool) – WhenTrue, extra keys inkey_order will be dropped ratherthan rendered with empty values.

  • bool_as_flag (bool) – WhenTrue, render{"flag":True} asflag, instead offlag=true.{"flag":False} is always rendered asflag=false.

Raises:

ValueError – If a key contains non-printable or whitespace characters.

Added in version 21.5.0.

>>>fromstructlog.processorsimportLogfmtRenderer>>>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'
classstructlog.processors.EventRenamer(to,replace_by=None)[source]#

Rename theevent key in event dicts.

This is useful if you want to use consistent log message keys acrossplatforms and/or use theevent key for something custom.

Warning

It’s recommended to put this processor right before the renderer, sincesome processors may rely on the presence and meaning of theeventkey.

Parameters:
  • to (str) – Renameevent_dict["event"] toevent_dict[to]

  • replace_by (str |None) – Renameevent_dict[replace_by] toevent_dict["event"].replace_by missing fromevent_dict is handled gracefully.

Added in version 22.1.0.

See also theRenaming the event key recipe.

structlog.processors.add_log_level(logger,method_name,event_dict)[source]#

Add the log level to the event dict under thelevel key.

Since that’s just the log method name, this processor works with non-stdliblogging as well. Therefore it’s importable both fromstructlog.processorsas well as fromstructlog.stdlib.

Added in version 15.0.0.

Changed in version 20.2.0:Importable fromstructlog.processors (additionally tostructlog.stdlib).

Changed in version 24.1.0:Added mapping from “exception” to “error”

classstructlog.processors.UnicodeDecoder(encoding='utf-8',errors='replace')[source]#

Decode byte string values inevent_dict.

Parameters:
  • encoding (str) – Encoding to decode from (default:"utf-8").

  • errors (str) – How to cope with encoding errors (default:"replace").

Useful to preventb"abc" being rendered as as'b"abc"'.

Just put it in the processor chain before the renderer.

Added in version 15.4.0.

classstructlog.processors.UnicodeEncoder(encoding='utf-8',errors='backslashreplace')[source]#

Encode unicode values inevent_dict.

Parameters:
  • encoding (str) – Encoding to encode to (default:"utf-8").

  • errors (str) – How to cope with encoding errors (default"backslashreplace").

Just put it in the processor chain before the renderer.

Note

Not very useful in a Python 3-only world.

classstructlog.processors.ExceptionRenderer(exception_formatter=<function_format_exception>)[source]#

Replace anexc_info field with anexception field which is renderedbyexception_formatter.

The contents of theexception field depends on the return value of theexception_formatter that is passed:

  • The default produces a formatted string via Python’s built-in tracebackformatting (this isformat_exc_info).

  • If you pass aExceptionDictTransformer, itbecomes a list of stack dicts that can be serialized to JSON.

Ifevent_dict contains the keyexc_info, there are three possiblebehaviors:

  1. If the value is a tuple, render it into the keyexception.

  2. If the value is an Exception render it into the keyexception.

  3. If the value true but no tuple, obtain exc_info ourselves and renderthat.

If there is noexc_info key, theevent_dict is not touched. Thisbehavior is analog to the one of the stdlib’s logging.

Parameters:

exception_formatter (ExceptionTransformer) – A callable that is used to format the exception from theexc_info field into theexception field.

See also

Exceptions for a broader explanation ofstructlog’s exceptionfeatures.

Added in version 22.1.0.

structlog.processors.format_exc_info(logger,name,event_dict)#

Replace anexc_info field with anexception string field using Python’sbuilt-in traceback formatting.

Ifevent_dict contains the keyexc_info, there are three possiblebehaviors:

  1. If the value is a tuple, render it into the keyexception.

  2. If the value is an Exception render it into the keyexception.

  3. If the value is true but no tuple, obtain exc_info ourselves and renderthat.

If there is noexc_info key, theevent_dict is not touched. This behavioris analog to the one of the stdlib’s logging.

See also

Exceptions for a broader explanation ofstructlog’s exceptionfeatures.

>>>fromstructlog.processorsimportformat_exc_info>>>try:...raiseValueError...exceptValueError:...format_exc_info(None,"",{"exc_info":True}){'exception': 'Traceback (most recent call last):...
structlog.processors.dict_tracebacks(logger,name,event_dict)#

Replace anexc_info field with anexception field containing structuredtracebacks suitable for, e.g., JSON output.

It is a shortcut forExceptionRenderer with aExceptionDictTransformer.

The treatment of theexc_info key is identical toformat_exc_info.

Added in version 22.1.0.

See also

Exceptions for a broader explanation ofstructlog’s exceptionfeatures.

>>>fromstructlog.processorsimportdict_tracebacks>>>try:...raiseValueError("onoes")...exceptValueError:...dict_tracebacks(None,"",{"exc_info":True}){'exception': [{'exc_type': 'ValueError', 'exc_value': 'onoes', ..., 'frames': [{'filename': ...
classstructlog.processors.StackInfoRenderer(additional_ignores=None)[source]#

Add stack information with keystack ifstack_info isTrue.

Useful when you want to attach a stack dump to a log entry withoutinvolving an exception and works analogously to thestack_info argumentof the Python standard library logging.

Parameters:

additional_ignores (list[str]|None) – By default, stack frames coming fromstructlog are ignored. Withthis argument you can add additional names that are ignored, beforethe stack starts being rendered. They are matched usingstartswith(), so they don’t have to match exactly. The namesare used to find the first relevant name, therefore once a frame isfound that doesn’t start withstructlog or one ofadditional_ignores,no filtering is applied to subsequentframes.

Added in version 0.4.0.

Added in version 22.1.0:additional_ignores

classstructlog.processors.ExceptionPrettyPrinter(file=None,exception_formatter=<function_format_exception>)[source]#

Pretty print exceptions rendered byexception_formatter and remove themfrom theevent_dict.

Parameters:
  • file (TextIO |None) – Target file for output (default:sys.stdout).

  • exception_formatter (ExceptionTransformer) – A callable that is used to format the exception from theexc_info field into theexception field.

This processor is mostly for development and testing so you can readexceptions properly formatted.

It behaves likeformat_exc_info, except that it removes the exception datafrom the event dictionary after printing it using the passedexception_formatter, which defaults to Python’s built-in traceback formatting.

It’s tolerant to havingformat_exc_info in front of itself in theprocessor chain but doesn’t require it. In other words, it handles bothexception as well asexc_info keys.

Added in version 0.4.0.

Changed in version 16.0.0:Added support for passing exceptions asexc_info on Python 3.

Changed in version 25.4.0:Fixedexception_formatter so that it overrides the default if set.

classstructlog.processors.TimeStamper(fmt=None,utc=True,key='timestamp')[source]#

Add a timestamp toevent_dict.

Parameters:
  • fmt (str |None) – strftime format string, or"iso" forISO 8601, orNone for aUNIXtimestamp.

  • utc (bool) – Whether timestamp should be in UTC or local time.

  • key (str) – Target key inevent_dict for added timestamps.

Changed in version 19.2.0:Can be pickled now.

>>>fromstructlog.processorsimportTimeStamper>>>TimeStamper()(None,"",{}){'timestamp': 1378994017}>>>TimeStamper(fmt="iso")(None,"",{}){'timestamp': '2013-09-12T13:54:26.996778Z'}>>>TimeStamper(fmt="%Y",key="year")(None,"",{}){'year': '2013'}
classstructlog.processors.MaybeTimeStamper(fmt=None,utc=True,key='timestamp')[source]#

A timestamper that only adds a timestamp if there is none.

This allows you to overwrite thetimestamp key in the event dict forexample when the event is coming from another system.

It takes the same arguments asTimeStamper.

Added in version 23.2.0.

>>>fromstructlog.processorsimportMaybeTimeStamper>>>MaybeTimeStamper()(None,"",{}){'timestamp': 1690036074.494428}>>>MaybeTimeStamper()(None,"",{"timestamp":42}){'timestamp': 42}
classstructlog.processors.CallsiteParameter(*values)[source]#

Callsite parameters that can be added to an event dictionary with thestructlog.processors.CallsiteParameterAdder processor class.

The string values of the members of this enum will be used as the keys forthe callsite parameters in the event dictionary.

Added in version 21.5.0.

Added in version 25.5.0:QUAL_NAME parameter.

FILENAME='filename'#

The basename part of the full path to the python source file of thecallsite.

FUNC_NAME='func_name'#

The name of the function that the callsite was in.

LINENO='lineno'#

The line number of the callsite.

MODULE='module'#

The python module the callsite was in. This mimics the module attributeoflogging.LogRecord objects and will be the basename, withoutextension, of the full path to the python source file of the callsite.

PATHNAME='pathname'#

The full path to the python source file of the callsite.

PROCESS='process'#

The ID of the process the callsite was executed in.

PROCESS_NAME='process_name'#

The name of the process the callsite was executed in.

QUAL_NAME='qual_name'#

The qualified name of the callsite (includes scope and class names).Requires Python 3.11+.

THREAD='thread'#

The ID of the thread the callsite was executed in.

THREAD_NAME='thread_name'#

The name of the thread the callsite was executed in.

classstructlog.processors.CallsiteParameterAdder(parameters={CallsiteParameter.FILENAME,CallsiteParameter.FUNC_NAME,CallsiteParameter.LINENO,CallsiteParameter.MODULE,CallsiteParameter.PATHNAME,CallsiteParameter.PROCESS,CallsiteParameter.PROCESS_NAME,CallsiteParameter.QUAL_NAME,CallsiteParameter.THREAD,CallsiteParameter.THREAD_NAME},additional_ignores=None)[source]#

Adds parameters of the callsite that an event dictionary originated from tothe event dictionary. This processor can be used to enrich eventsdictionaries with information such as the function name, line number andfilename that an event dictionary originated from.

If the event dictionary has an embeddedlogging.LogRecord object and didnot originate fromstructlog then the callsite information will bedetermined from thelogging.LogRecord object. For event dictionarieswithout an embeddedlogging.LogRecord object the callsite will bedetermined from the stack trace, ignoring all intra-structlog calls, callsfrom thelogging module, and stack frames from modules with names thatstart with values inadditional_ignores, if it is specified.

The keys used for callsite parameters in the event dictionary are thestring values ofCallsiteParameter enum members.

Parameters:
  • parameters (Collection[CallsiteParameter]) – A collection ofCallsiteParameter values that should be added tothe event dictionary.

  • additional_ignores (list[str]|None) – Additional names with which a stack frame’s module name must notstart for it to be considered when determening the callsite.

Note

When used withstructlog.stdlib.ProcessorFormatter the most efficientconfiguration is to either use this processor inforeign_pre_chainofstructlog.stdlib.ProcessorFormatter and inprocessors ofstructlog.configure, or to use it inprocessors ofstructlog.stdlib.ProcessorFormatter without using it inprocessors ofstructlog.configure andforeign_pre_chain ofstructlog.stdlib.ProcessorFormatter.

Added in version 21.5.0.

structlog.stdlib Module#

Processors and helpers specific to thelogging module from thePythonstandard library.

See alsostructlog’s standard library support.

structlog.stdlib.recreate_defaults(*,log_level=0)[source]#

Recreate defaults on top of standard library’s logging.

The output looks the same, but goes throughlogging.

As with vanilla defaults, the backwards-compatibility guarantees don’tapply to the settings applied here.

Parameters:

log_level (int |None) –

IfNone, don’t configure standard library loggingat all.

Otherwise configure it to log tosys.stdout atlog_level(logging.NOTSET being the default).

If you need more control overlogging, passNone here andconfigure it yourself.

Added in version 22.1.0.

Changed in version 23.3.0:Addedadd_logger_name.

Changed in version 25.1.0:AddedPositionalArgumentsFormatter.

structlog.stdlib.get_logger(*args,**initial_values)[source]#

Only callsstructlog.get_logger, but has the correct type hints.

Warning

Doesnot check whether – or ensure that – you’ve configuredstructlog for standard librarylogging!

SeeStandard Library Logging for details.

Added in version 20.2.0.

classstructlog.stdlib.BoundLogger(logger,processors,context)[source]#

Python Standard Library version ofstructlog.BoundLogger.

Works exactly like the generic one except that it takes advantage ofknowing the logging methods in advance.

Use it like:

structlog.configure(wrapper_class=structlog.stdlib.BoundLogger,)

It also contains a bunch of properties that pass-through to the wrappedlogging.Logger which should make it work as a drop-in replacement.

Added in version 23.1.0:Async variantsalog(),adebug(),ainfo(), and so forth.

Changed in version 24.2.0:Callsite parameters are now also collected bystructlog.processors.CallsiteParameterAdder for async log methods.

asyncacritical(event,*args,**kw)[source]#

Log usingcritical(), but asynchronously in a separate thread.

Added in version 23.1.0.

asyncadebug(event,*args,**kw)[source]#

Log usingdebug(), but asynchronously in a separate thread.

Added in version 23.1.0.

asyncaerror(event,*args,**kw)[source]#

Log usingerror(), but asynchronously in a separate thread.

Added in version 23.1.0.

asyncaexception(event,*args,**kw)[source]#

Log usingexception(), but asynchronously in a separate thread.

Added in version 23.1.0.

asyncainfo(event,*args,**kw)[source]#

Log usinginfo(), but asynchronously in a separate thread.

Added in version 23.1.0.

asyncalog(level,event,*args,**kw)[source]#

Log usinglog(), but asynchronously in a separate thread.

Added in version 23.1.0.

asyncawarning(event,*args,**kw)[source]#

Log usingwarning(), but asynchronously in a separate thread.

Added in version 23.1.0.

bind(**new_values)[source]#

Return a new logger withnew_values added to the existing ones.

critical(event=None,*args,**kw)[source]#

Process event and calllogging.Logger.critical with the result.

debug(event=None,*args,**kw)[source]#

Process event and calllogging.Logger.debug with the result.

error(event=None,*args,**kw)[source]#

Process event and calllogging.Logger.error with the result.

exception(event=None,*args,**kw)[source]#

Process event and calllogging.Logger.exception with the result,after settingexc_info toTrue if it’s not already set.

info(event=None,*args,**kw)[source]#

Process event and calllogging.Logger.info with the result.

log(level,event=None,*args,**kw)[source]#

Processevent and call the appropriate logging method depending onlevel.

new(**new_values)[source]#

Clear context and bindsinitial_values usingbind.

Only necessary with dict implementations that keep global state likethose wrapped bystructlog.threadlocal.wrap_dict when threadsare reused.

try_unbind(*keys)[source]#

Likeunbind(), but best effort: missing keys are ignored.

Added in version 18.2.0.

unbind(*keys)[source]#

Return a new logger withkeys removed from the context.

Raises:

KeyError – If the key is not part of the context.

warn(event=None,*args,**kw)#

Process event and calllogging.Logger.warning with the result.

warning(event=None,*args,**kw)[source]#

Process event and calllogging.Logger.warning with the result.

classstructlog.stdlib.AsyncBoundLogger(logger,processors,context,*,_sync_bl=None,_loop=None)[source]#

Wraps aBoundLogger & exposes its logging methods asasync versions.

Instead of blocking the program, they are run asynchronously in a threadpool executor.

This means more computational overhead per log call. But it also means thatthe processor chain (e.g. JSON serialization) and I/O won’t block yourwhole application.

Only available for Python 3.7 and later.

Added in version 20.2.0.

Changed in version 20.2.0:fix _dispatch_to_sync contextvars usage

Deprecated since version 23.1.0:Use the regularBoundLogger with its a-prefixed methods instead.

Changed in version 23.3.0:Callsite parameters are now also collected for async log methods.

sync_bl:BoundLogger#

The wrapped synchronous logger. It is useful to be able to logsynchronously occasionally.

classstructlog.stdlib.LoggerFactory(ignore_frame_names=None)[source]#

Build a standard library logger when aninstance is called.

Sets a custom logger usinglogging.setLoggerClass() so variables inlog format are expanded properly.

>>>fromstructlogimportconfigure>>>fromstructlog.stdlibimportLoggerFactory>>>configure(logger_factory=LoggerFactory())
Parameters:

ignore_frame_names (list[str]|None) – When guessing the name of a logger, skip frames whose namesstartwith one of these. For example, in pyramid applications you’llwant to set it to["venusian","pyramid.config"]. This argumentis calledadditional_ignores in other APIs throughoutstructlog.

__call__(*args)[source]#

Deduce the caller’s module name and create a stdlib logger.

If an optional argument is passed, it will be used as the logger nameinstead of guesswork. This optional argument would be passed from thestructlog.get_logger() call. For examplestructlog.get_logger("foo") would cause this method to be calledwith"foo" as its first positional argument.

Changed in version 0.4.0:Added support for optional positional arguments. Using the firstone for naming the constructed logger.

structlog.stdlib.render_to_log_args_and_kwargs(_,__,event_dict)[source]#

Renderevent_dict into positional and keyword arguments forlogging.Logger logging methods.Seelogging.Logger.debug method for keyword arguments reference.

Theevent field is passed in the first positional argument, positionalarguments frompositional_args field are passed in subsequent positionalarguments, keyword arguments are extracted from theevent_dict and therest of theevent_dict is added asextra.

This allows you to defer formatting tologging.

Added in version 25.1.0.

structlog.stdlib.render_to_log_kwargs(_,__,event_dict)[source]#

Renderevent_dict into keyword arguments forlogging.Logger loggingmethods.Seelogging.Logger.debug method for keyword arguments reference.

Theevent field is translated intomsg, keyword arguments areextracted from theevent_dict and the rest of theevent_dict is added asextra.

This allows you to defer formatting tologging.

Added in version 17.1.0.

Changed in version 22.1.0:exc_info,stack_info, andstacklevel are passed as properkwargs and not put intoextra.

Changed in version 24.2.0:stackLevel corrected tostacklevel.

structlog.stdlib.filter_by_level(logger,method_name,event_dict)[source]#

Check whether logging is configured to accept messages from this log level.

Should be the first processor if stdlib’s filtering by level is used sopossibly expensive processors like exception formatters are avoided in thefirst place.

>>>importlogging>>>fromstructlog.stdlibimportfilter_by_level>>>logging.basicConfig(level=logging.WARN)>>>logger=logging.getLogger()>>>filter_by_level(logger,'warn',{}){}>>>filter_by_level(logger,'debug',{})Traceback (most recent call last):...DropEvent
structlog.stdlib.add_log_level(logger,method_name,event_dict)[source]#

Add the log level to the event dict under thelevel key.

Since that’s just the log method name, this processor works with non-stdliblogging as well. Therefore it’s importable both fromstructlog.processorsas well as fromstructlog.stdlib.

Added in version 15.0.0.

Changed in version 20.2.0:Importable fromstructlog.processors (additionally tostructlog.stdlib).

Changed in version 24.1.0:Added mapping from “exception” to “error”

structlog.stdlib.add_log_level_number(logger,method_name,event_dict)[source]#

Add the log level number to the event dict.

Log level numbers map to the log level names. The Python stdlib uses themfor filtering logic. This adds the same numbers so users can leveragesimilar filtering. Compare:

levelin("warning","error","critical")level_number>=30

The mapping of names to numbers is instructlog.stdlib._log_levels._NAME_TO_LEVEL.

Added in version 18.2.0.

structlog.stdlib.add_logger_name(logger,method_name,event_dict)[source]#

Add the logger name to the event dict.

classstructlog.stdlib.ExtraAdder(allow=None)[source]#

Add extra attributes oflogging.LogRecord objects to the eventdictionary.

This processor can be used for adding data passed in theextraparameter of thelogging module’s log methods to the event dictionary.

Parameters:

allow (Collection[str]|None) –

An optional collection of attributes that, if present inlogging.LogRecord objects, will be copied to event dictionaries.

Ifallow is None all attributes oflogging.LogRecord objectsthat do not exist on a standardlogging.LogRecord object will becopied to event dictionaries.

Added in version 21.5.0.

classstructlog.stdlib.PositionalArgumentsFormatter(remove_positional_args=True)[source]#

Apply stdlib-like string formatting to theevent key.

If thepositional_args key in the event dict is set, it mustcontain a tuple that is used for formatting (using the%s stringformatting operator) of the value from theevent key. This worksin the same way as the stdlib handles arguments to the various logmethods: if the tuple contains only a singledict argument it isused for keyword placeholders in theevent string, otherwise itwill be used for positional placeholders.

positional_args is populated bystructlog.stdlib.BoundLogger orcan be set manually.

Theremove_positional_args flag can be set toFalse to keep thepositional_args key in the event dict; by default it will beremoved from the event dict after formatting a message.

classstructlog.stdlib.ProcessorFormatter(processor=None,processors=(),foreign_pre_chain=None,keep_exc_info=False,keep_stack_info=False,logger=None,pass_foreign_args=False,use_get_message=True,*args,**kwargs)[source]#

Callstructlog processors onlogging.LogRecords.

This is an implementation of alogging.Formatter that can be used toformat log entries from bothstructlog andlogging.

Its static methodwrap_for_formatter must be the final processor instructlog’s processor chain.

Please refer toRendering using structlog-based formatters within logging for examples.

Parameters:
  • foreign_pre_chain (Sequence[Processor]|None) – If notNone, it is used as a processor chain that is applied tonon-structlog log entries before the event dictionary ispassed toprocessors. (default:None)

  • processors (Sequence[Processor]|None) –

    A chain ofstructlog processors that is used to processalllog entries. The last one must render to astr which then getspassed on tologging for output.

    Compared tostructlog’s regular processor chains, there’s a fewdifferences:

    • The event dictionary contains two additional keys:

      1. _record: alogging.LogRecord that either was created

        usinglogging APIs,or is a wrappedstructlog logentry created bywrap_for_formatter.

      2. _from_structlog: abool that indicates whether or not_record was created by astructlog logger.

      Since you most likely don’t want_record and_from_structlog in your log files, we’ve added the staticmethodremove_processors_meta toProcessorFormatter thatyou can add just before your renderer.

    • Since this is aloggingformatter, raisingstructlog.DropEvent will crash your application.

  • keep_exc_info (bool) –exc_info onlogging.LogRecords is added to theevent_dict and removed afterwards. Set this toTrue to keepit on thelogging.LogRecord. (default: False)

  • keep_stack_info (bool) – Same askeep_exc_info except forstack_info. (default: False)

  • logger (logging.Logger |None) – Logger which we want to push through thestructlog processorchain. This parameter is necessary for some of the processors likefilter_by_level. (default: None)

  • pass_foreign_args (bool) – If True, pass a foreign log record’sargs attribute to theevent_dict underpositional_args key. (default: False)

  • processor (Processor |None) –

    A singlestructlog processor used for rendering the eventdictionary before passing it off tologging. Must return astr.The event dictionary doesnot contain_record and_from_structlog.

    This parameter exists for historic reasons. Please useprocessorsinstead.

  • use_get_message (bool) – If True, userecord.getMessage to get a fully rendered logmessage, otherwise usestr(record.msg). (default: True)

Raises:

TypeError – If both or neitherprocessor andprocessors are passed.

Added in version 17.1.0.

Added in version 17.2.0:keep_exc_info andkeep_stack_info

Added in version 19.2.0:logger

Added in version 19.2.0:pass_foreign_args

Added in version 21.3.0:processors

Deprecated since version 21.3.0:processor (singular) in favor ofprocessors (plural). Removal is notplanned.

Added in version 23.3.0:use_get_message

staticremove_processors_meta(_,__,event_dict)[source]#

Remove_record and_from_structlog fromevent_dict.

These keys are added to the event dictionary, beforeProcessorFormatter’sprocessors are run.

Added in version 21.3.0.

staticwrap_for_formatter(logger,name,event_dict)[source]#

Wraplogger,name, andevent_dict.

The result is later unpacked byProcessorFormatter when formattinglog entries.

Use this static method as the renderer (in other words, finalprocessor) if you want to useProcessorFormatter in yourloggingconfiguration.

structlog.tracebacks Module#

Extract a structured traceback from an exception.

Based on work by Will McGugan<hynek/structlog#407>`_ fromrich.traceback.

structlog.tracebacks.extract(exc_type,exc_value,traceback,*,show_locals=False,locals_max_length=10,locals_max_string=80,locals_hide_dunder=True,locals_hide_sunder=False,use_rich=True,_seen=None)[source]#

Extract traceback information.

Parameters:
  • exc_type (type[BaseException]) – Exception type.

  • exc_value (BaseException) – Exception value.

  • traceback (TracebackType |None) – Python Traceback object.

  • show_locals (bool) – Enable display of local variables. Defaults to False.

  • locals_max_length (int) – Maximum length of containers before abbreviating, orNone forno abbreviation.

  • locals_max_string (int) – Maximum length of string before truncating, orNone to disabletruncating.

  • locals_hide_dunder (bool) – Hide locals prefixed with double underscore.Defaults to True.

  • locals_hide_sunder (bool) – Hide locals prefixed with single underscore.This implies hidinglocals_hide_dunder.Defaults to False.

  • use_rich (bool) – IfTrue (the default), userich to compute the repr.IfFalse or ifrich is not installed, fall back to a simpleralgorithm.

Returns:

A Trace instance with structured information about all exceptions.

Return type:

Trace

Added in version 22.1.0.

Changed in version 24.3.0:Addedlocals_max_length,locals_hide_sunder,locals_hide_dunderanduse_rich arguments.

Changed in version 25.4.0:Handle exception groups.

Changed in version 25.5.0:Handle loops in exception cause chain.

classstructlog.tracebacks.ExceptionDictTransformer(*,show_locals=True,locals_max_length=10,locals_max_string=80,locals_hide_dunder=True,locals_hide_sunder=False,suppress=(),max_frames=50,use_rich=True)[source]#

Return a list of exception stack dictionaries for an exception.

These dictionaries are based onStack instances generated byextract() and can be dumped to JSON.

Parameters:
  • show_locals (bool) – Whether or not to include the values of a stack frame’s localvariables.

  • locals_max_length (int) – Maximum length of containers before abbreviating, orNone forno abbreviation.

  • locals_max_string (int) – Maximum length of string before truncating, orNone to disabletruncating.

  • locals_hide_dunder (bool) – Hide locals prefixed with double underscore.Defaults to True.

  • locals_hide_sunder (bool) – Hide locals prefixed with single underscore.This implies hidinglocals_hide_dunder.Defaults to False.

  • suppress (Iterable[str |ModuleType]) – Optional sequence of modules or paths for which to suppress thedisplay of locals even ifshow_locals isTrue.

  • max_frames (int) – Maximum number of frames in each stack. Frames are removed fromthe inside out. The idea is, that the first frames represent yourcode responsible for the exception and last frames the code wherethe exception actually happened. With larger web frameworks, thisdoes not always work, so you should stick with the default.

  • use_rich (bool) – IfTrue (the default), userich to compute the repr oflocals. IfFalse or ifrich is not installed, fall back toa simpler algorithm.

See also

Exceptions for a broader explanation ofstructlog’s exceptionfeatures.

Changed in version 24.3.0:Addedlocals_max_length,locals_hide_sunder,locals_hide_dunder,suppress anduse_rich arguments.

Changed in version 25.1.0:locals_max_length andlocals_max_string may be None to disabletruncation.

Changed in version 25.4.0:Handle exception groups.

classstructlog.tracebacks.Trace(stacks)[source]#

Container for a list of stack traces.

classstructlog.tracebacks.Stack(exc_type,exc_value,exc_notes=<factory>,syntax_error=None,is_cause=False,frames=<factory>,is_group=False,exceptions=<factory>)[source]#

Represents an exception and a list of stack frames.

Changed in version 25.2.0:Added theexc_notes field.

Changed in version 25.4.0:Added theis_group andexceptions fields.

classstructlog.tracebacks.Frame(filename,lineno,name,locals=None)[source]#

Represents a single stack frame.

classstructlog.tracebacks.SyntaxError_(offset,filename,line,lineno,msg)[source]#

Contains detailed information aboutSyntaxError exceptions.

structlog.typing Module#

Type information used throughoutstructlog.

For now, they are considered provisional. EspeciallyBindableLogger willprobably change to something more elegant.

Added in version 22.2.0.

classstructlog.typing.BindableLogger(*args,**kwargs)[source]#

Protocol: Methods shared among all bound loggers and that are relied onbystructlog.

Added in version 20.2.0.

Additionally to the methods listed below, bound loggersmust have a__init__ method with the following signature:

__init__(self,wrapped_logger:WrappedLogger,processors:Iterable[Processor],context:Context)None

Unfortunately it’s impossible to define initializers usingPEP 544 Protocols.

They currently also have to carry aContext as a_context attribute.

Note

Currently Sphinx has no support for Protocols, so please click[source] for this entry to see the full definition.

classstructlog.typing.FilteringBoundLogger(*args,**kwargs)[source]#

Protocol: ABindableLogger that filters by a level.

The only way to instantiate one is usingmake_filtering_bound_logger.

Added in version 20.2.0.

Added in version 22.2.0:String interpolation using positional arguments.

Added in version 22.2.0:Async variantsalog(),adebug(),ainfo(), and so forth.

Changed in version 22.3.0:String interpolation is only attempted if positional arguments arepassed.

Added in version 25.5.0:String interpolation using dictionary-based arguments if the first andonly argument is a mapping.

Note

Currently Sphinx has no support for Protocols, so please click[source] for this entry to see the full definition.

classstructlog.typing.ExceptionTransformer(*args,**kwargs)[source]#

Protocol: A callable that transforms anExcInfo into anotherdatastructure.

The result should be something that your renderer can work with, e.g., astr or a JSON-serializabledict.

Used bystructlog.processors.format_exc_info() andstructlog.processors.ExceptionPrettyPrinter.

Parameters:

exc_info – Is the exception tuple to format

Returns:

Anything that can be rendered by the last processor in your chain, forexample, a string or a JSON-serializable structure.

Added in version 22.1.0.

Note

Currently Sphinx has no support for Protocols, so please click[source] for this entry to see the full definition.

structlog.typing.EventDict#

An event dictionary as it is passed into processors.

It’s created by copying the configuredContext but doesn’t need to supportcopy itself.

Added in version 20.2.0.

alias ofMutableMapping[str,Any]

structlog.typing.WrappedLogger=typing.Any#

A logger that is wrapped by a bound logger and is ultimately responsible forthe output of the log entries.

structlog makesno assumptions about it.

Added in version 20.2.0.

structlog.typing.Processor#

A callable that is part of the processor chain.

SeeProcessors.

Added in version 20.2.0.

alias ofCallable[[Any,str,MutableMapping[str,Any]],Mapping[str,Any] |str |bytes |bytearray |Tuple[Any, …]]

structlog.typing.Context#

A dict-like context carrier.

Added in version 20.2.0.

alias ofDict[str,Any] |Dict[Any,Any]

structlog.typing.ExcInfo#

An exception info tuple as returned bysys.exc_info.

Added in version 20.2.0.

alias ofTuple[Type[BaseException],BaseException,TracebackType |None]

structlog.typing.ExceptionRenderer#

A callable that pretty-prints anExcInfo into a file-like object.

Used bystructlog.dev.ConsoleRenderer.

Added in version 21.2.0.

alias ofCallable[[TextIO,Tuple[Type[BaseException],BaseException,TracebackType |None]],None]

structlog.twisted Module#

Processors and tools specific to theTwistednetworking engine.

See alsostructlog’s Twisted support.

classstructlog.twisted.BoundLogger(logger,processors,context)[source]#

Twisted-specific version ofstructlog.BoundLogger.

Works exactly like the generic one except that it takes advantage ofknowing the logging methods in advance.

Use it like:

configure(wrapper_class=structlog.twisted.BoundLogger,)
bind(**new_values)#

Return a new logger withnew_values added to the existing ones.

err(event=None,**kw)[source]#

Process event and calllog.err() with the result.

msg(event=None,**kw)[source]#

Process event and calllog.msg() with the result.

new(**new_values)#

Clear context and bindsnew_values usingbind.

Only necessary with dict implementations that keep global state likethose wrapped bystructlog.threadlocal.wrap_dict when threadsare reused.

unbind(*keys)#

Return a new logger withkeys removed from the context.

Raises:

KeyError – If the key is not part of the context.

classstructlog.twisted.LoggerFactory[source]#

Build a Twisted logger when aninstance is called.

>>>fromstructlogimportconfigure>>>fromstructlog.twistedimportLoggerFactory>>>configure(logger_factory=LoggerFactory())
__call__(*args)[source]#

Positional arguments are silently ignored.

Rvalue:

A new Twisted logger.

Changed in version 0.4.0:Added support for optional positional arguments.

classstructlog.twisted.EventAdapter(dictRenderer=None)[source]#

Adapt anevent_dict to Twisted logging system.

Particularly, make a wrappedtwisted.python.log.errbehave as expected.

Parameters:

dictRenderer (Callable[[WrappedLogger,str,EventDict],str]|None) – Renderer that is used for the actual log message. Please note thatstructlog comes with a dedicatedJSONRenderer.

Must be the last processor in the chain and requires adictRendererfor the actual formatting as an constructor argument in order to be able tofully support the original behaviors oflog.msg() andlog.err().

classstructlog.twisted.JSONRenderer(serializer=<functiondumps>,**dumps_kw)[source]#

Behaves likestructlog.processors.JSONRenderer except that it formatstracebacks and failures itself if called witherr().

Note

This ultimately means that the messages get logged out usingmsg(),andnoterr() which renders failures in separate lines.

Therefore it will break your tests that contain assertions usingflushLoggedErrors.

Not an adapter likeEventAdapter but a real formatter. Also doesnotrequire to be adapted using it.

Use together with aJSONLogObserverWrapper-wrapped Twisted logger likeplainJSONStdOutLogger for pure-JSON logs.

structlog.twisted.plainJSONStdOutLogger()[source]#

Return a logger that writes only the message to stdout.

Transforms non-JSONRenderer messages to JSON.

Ideal for JSONifying log entries from Twisted plugins and libraries thatare outside of your control:

$ twistd -n --logger structlog.twisted.plainJSONStdOutLogger web{"event": "Log opened.", "system": "-"}{"event": "twistd 13.1.0 (python 2.7.3) starting up.", "system": "-"}{"event": "reactor class: twisted...EPollReactor.", "system": "-"}{"event": "Site starting on 8080", "system": "-"}{"event": "Starting factory <twisted.web.server.Site ...>", ...}...

ComposesPlainFileLogObserver andJSONLogObserverWrapper to a usablelogger.

Added in version 0.2.0.

structlog.twisted.JSONLogObserverWrapper(observer)[source]#

Wrap a logobserver and render non-JSONRenderer entries to JSON.

Parameters:

observer (ILogObserver) – Twisted log observer to wrap. For examplePlainFileObserver or Twisted’s stockFileLogObserver

Added in version 0.2.0.

classstructlog.twisted.PlainFileLogObserver(file)[source]#

Write only the plain message without timestamps or anything else.

Great to just print JSON to stdout where you catch it with something likerunit.

Parameters:

file (TextIO) – File to print to.

Added in version 0.2.0.

Contents