Convenience function that returns a logger according to configuration.
>>> from structlog import get_logger
>>> log = get_logger(y=23)
>>> log.msg('hello', x=42)
y=23 x=42 event='hello'
Parameters: | initial_values – Values that are used to pre-populate your contexts. |
---|
See Configuration for details.
If you prefer CamelCase, there’s an alias for your reading pleasure: structlog.getLogger().
CamelCase alias for structlog.get_logger().
This function is supposed to be in every source file – I don’t want it to stick out like a sore thumb in frameworks like Twisted or Zope.
Create a new bound logger for an arbitrary logger.
Default values for processors, wrapper_class, and context_class can be set using configure().
If you set processors or context_class here, calls to configure() have no effect for the respective attribute.
In other words: selective overwriting of the defaults is possible.
Parameters: |
|
---|---|
Return type: | A proxy that creates a correctly configured bound logger when necessary. |
Configures the global defaults.
They are used if wrap_logger() has been called without arguments.
Also sets the global class attribute is_configured to True on first call. Can be called several times, keeping an argument at None leaves is unchanged from the current setting.
Use reset_defaults() to undo your changes.
Parameters: |
|
---|
Configures iff structlog isn’t configured yet.
It does not matter whether is was configured using configure() or configure_once() before.
Raises a RuntimeWarning if repeated configuration is attempted.
Resets global default values to builtins.
That means [format_exc_info(), KeyValueRenderer] for processors, BoundLogger for wrapper_class, OrderedDict for context_class, and PrintLogger for logger_factory.
Also sets the global class attribute is_configured to True.
Immutable, context-carrying wrapper.
Public only for sub-classing, not intended to be instantiated by yourself. See wrap_logger() and get_logger().
Clear context and binds initial_values using bind().
Only necessary with dict implementations that keep global state like those wrapped by structlog.threadlocal.wrap_dict() when threads are re-used.
Return type: | BoundLogger |
---|
Return a new logger with new_values added to the existing ones.
Return type: | BoundLogger |
---|
Return a new logger with keys removed from the context.
Raises KeyError: | |
---|---|
If the key is not part of the context. | |
Return type: | BoundLogger |
Prints events into a file.
Parameters: | file (file) – File to print to. (default: stdout) |
---|
>>> from structlog import PrintLogger
>>> PrintLogger().msg('hello')
hello
Useful if you just capture your stdout with tools like runit or if you forward your stderr to syslog.
Also very useful for testing and examples since logging is sometimes finicky in doctests.
Returns the string that it’s called with.
>>> from structlog import ReturnLogger
>>> ReturnLogger().msg('hello')
'hello'
Useful for unit tests.
If raised by an processor, the event gets silently dropped.
Derives from BaseException because it’s technically not an error.
Primitives to keep context global but thread (and greenlet) local.
Wrap a dict-like class and return the resulting class.
The wrapped class and used to keep global in the current thread.
Parameters: | dict_class (type) – Class used for keeping context. |
---|---|
Return type: | type |
Bind tmp_values to logger & memorize current state. Rewind afterwards.
>>> from structlog import wrap_logger, PrintLogger
>>> from structlog.threadlocal import tmp_bind, wrap_dict
>>> logger = wrap_logger(PrintLogger(), context_class=wrap_dict(dict))
>>> with tmp_bind(logger, x=5) as tmp_logger:
... logger = logger.bind(y=3)
... tmp_logger.msg('event')
y=3 x=5 event='event'
>>> logger.msg('event')
event='event'
Extract the context from a thread local logger into an immutable logger.
Parameters: | logger (BoundLogger) – A logger with possibly thread local state. |
---|---|
Return type: | BoundLogger with an immutable context. |
Processors useful regardless of the logging framework.
Bases: object
Render the event_dict using json.dumps(event_dict, **json_kw).
>>> from structlog.processors import JSONRenderer
>>> JSONRenderer(sort_keys=True)(None, None, {'a': 42, 'b': [1, 2, 3]})
'{"a": 42, "b": [1, 2, 3]}'
Bases: object
Render event_dict as a list of Key=repr(Value) pairs.
>>> from structlog.processors import KeyValueRenderer
>>> KeyValueRenderer()(None, None, {'a': 42, 'b': [1, 2, 3]})
'a=42 b=[1, 2, 3]'
Parameters: | sort_keys (bool) – Whether to sort keys when formatting. |
---|
Bases: object
Add a timestamp to event_dict.
Parameters: |
|
---|
>>> from structlog.processors import TimeStamper
>>> TimeStamper()(None, None, {})
{'timestamp': 1378994017}
>>> TimeStamper(fmt='iso')(None, None, {})
{'timestamp': '2013-09-12T13:54:26.996778Z'}
>>> TimeStamper(fmt='%Y')(None, None, {})
{'timestamp': '2013'}
Bases: object
Encode unicode values in event_dict.
Useful for KeyValueRenderer if you don’t want to see u-prefixes:
>>> from structlog.processors import KeyValueRenderer, UnicodeEncoder
>>> KeyValueRenderer()(None, None, {'foo': u'bar'})
"foo=u'bar'"
>>> KeyValueRenderer()(None, None,
... UnicodeEncoder()(None, None, {'foo': u'bar'}))
"foo='bar'"
Just put it in the processor chain before KeyValueRenderer.
Replace an exc_info field by an exception string field:
If event_dict contains the key exc_info, there are two possible behaviors:
If there is no exc_info key, the event_dict is not touched. This behavior is analogue to the one of the stdlib’s logging.
>>> from structlog.processors import format_exc_info
>>> try:
... raise ValueError
... except ValueError:
... format_exc_info(None, None, {'exc_info': True})
{'exception': 'Traceback (most recent call last):...
Processors and helpers specific to the logging module from the Python standard library.
Build a standard library logger when an instance is called.
>>> from structlog import configure
>>> from structlog.stdlib import LoggerFactory
>>> configure(logger_factory=LoggerFactory())
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 so possibly expensive processors like exception formatters are avoided in the first place.
>>> import logging
>>> from structlog.stdlib import filter_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
Processors and tools specific to the Twisted networking engine.
Build a Twisted logger when an instance is called.
>>> from structlog import configure
>>> from structlog.twisted import LoggerFactory
>>> configure(logger_factory=LoggerFactory())
Adapt an event_dict to Twisted logging system.
Particularly, make a wrapped twisted.python.log.err behave as expected.
Must be the last processor in the chain and requires a dictFormatter for the actual formatting as an constructor argument in order to be able to fully support the original behaviors of log.msg() and log.err().
Behaves like structlog.processors.JSONRenderer except that it formats tracebacks and failures itself if called with err().
Not an adapter like EventAdapter but a real formatter. Nor does it require to be adapted using it.