Functions¶
- clear() None [source]¶
Clear all existing loggers, handlers and formatters.
This function also closes all existing handlers.
- configure(config_dict: _DictConfig, /, context_var: ContextVar = LOG_CONTEXT) Logger [source]¶
Configure loggers for a configuration dict.
- Parameters:
config_dict – logging configuration (JSON compatible), at module init this function is called with uvlog.BASIC_CONFIG to provide default loggers and handlers
context_var – log context variable, see contextvars
This function is similar to dictConfig in the standard logging module, although the config format is slightly different.
{ "loggers": { "app": { "level": "ERROR", "handlers": ["my_file.txt"], "capture_trace": True } }, "handlers": { "my_file.txt": { "class": "StreamHandler", "level": "DEBUG", "formatter": "my_format" } }, "formatters": { "my_format": { "class": "TextFormatter", "format": "{name}: {message}" } } }
The main differences are:
- ‘class’ names for handlers and formatters must be registered beforehand using ‘add_formatter_type()’ and
‘add_handler_type()’ respectively to allow classes not inherited from Handler / ‘Formatter`
- handler names are their destinations, since by design you’re not allowed to bind multiple handlers to a single
destination
‘format’ for the text formatter should be in Python f-string format
Attention
The function is designed in such way you can extend or modify existing loggers, handlers or formatters by passing a config. If you want to configure logging from zero you should call clear() method beforehand. Please note that you need to provide all the handlers, formatters, loggers in the config after doing that, including the root logger (empty string).
- get_logger(name: str = _root_logger_name, /, *, persistent: bool = False) Logger [source]¶
Get an existing logger or create a new one.
- Parameters:
name – logger full name, for example ‘app.services.my_service’, by default returns the root logger
persistent – make this logger persistent and store it forever
Attention
Contrary to Python default logging module, this function by default produces a non-persistent logger unless it has been created using uvlog.configure(). This means that once no existing references exist for this logger, it will be garbage-collected.
Loggers¶
- class Logger[source]¶
Logger object.
It can be used almost like a standard Python logger, except that it allows passing keyword arguments directly to extra:
main_logger = uvlog.get_logger('app') logger = main_logger.get_child('my_service') logger.debug('debug message', debug_value=42) logger.error('error happened', exc_info=Exception())
- name: str¶
Logger name
- level: Literal['NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL', 'NEVER'] = 'INFO'¶
Logging level
- sample_rate: float = 1.0¶
Log records sample rate which determines a probability at which a record should be sampled.
Sample rate is not considered for levels above ‘INFO’. Values >= 1 disable the sampling mechanism.
- sample_propagate: bool = True¶
By default the sampling mechanism is contextual meaning that if there’s a non-empty log context, the log chain is marked ‘sampled’ as it sampled by the first logger in a chain. Once a record is ‘sampled’ the log chain cannot be unsampled, i.e. all subsequent loggers will be forced to sample it as well. It allows to preserve an entire request log chain in the logs and not just some random not connected logs.
- context: ContextVar[Dict[str, Any] | None] = <ContextVar name='LOG_CONTEXT' default=None>¶
Log context variable - useful for contextual data, see contextvars
- capture_trace: bool = False¶
Capture traceback for each call such as line numbers, file names etc. — may affect performance
- set_level(level: Literal['NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL', 'NEVER'], /) None [source]¶
- getChild(name: str, /) Logger [source]¶
Get or create a child logger.
This is a compatibility wrapper around
get_child()
. Use that method instead.
- get_child(name: str, /, *, persistent: bool = False) Logger [source]¶
Get or create a child logger inheriting all the logger settings.
Attention
Note that by default a new logger is not persistent, i.e. it will be eventually garbage collected if there are no live references to it.
- never(msg: str, /, *args, exc_info: Exception | None = None, stack_info=None, stacklevel=1, **kws) None [source]¶
- critical(msg: str, /, *args, exc_info: Exception | None = None, stack_info=None, stacklevel=1, **kws) None [source]¶
- error(msg: str, /, *args, exc_info: Exception | None = None, stack_info=None, stacklevel=1, **kws) None [source]¶
- warning(msg: str, /, *args, exc_info: Exception | None = None, stack_info=None, stacklevel=1, **kws) None [source]¶
- class LogRecord[source]¶
Log record object.
A log record object is created when a log method of a logger is called.
- name: str¶
Logger name
- level: Literal['NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL', 'NEVER']¶
Log record level name
- levelno: int¶
Log record level number
- asctime: datetime¶
Timestamp of record creation
- message: str¶
Log message
- exc_info: Exception | None¶
Exception (if any)
- args: tuple | None¶
Log call positional arguments.
This attribute is left only for compatibility reasons. It’s not used in formatting log messages.
- extra: Mapping[str, Any] | None¶
Log extra information provided in kwargs
- ctx: Mapping[str, Any] | None¶
Log contextual information
- filename: str | None¶
Filename of the caller
- func: str | None¶
Function name of the caller
- lineno: int | None¶
Source code line number of the caller
Handlers¶
- class Handler[source]¶
Log handler interface.
It’s a protocol class, i.e. one doesn’t need to inherit from it to create a valid handler.
- route_prefix: ClassVar[str]¶
- abstract classmethod resolve_destination(route: str, /) str [source]¶
Resolve destination route and normalize it.
- class QueueHandler[source]¶
Logging handler with an internal queue.
The handler uses a separate thread to write logs to the buffer via the
write()
method. Note that this handler doesn’t use any internal locks, because it’s expected by design that each handler has its own destination.- queue_size: int¶
Log queue size, infinite by default
- batch_size: int¶
Maximum number of log records to concatenate and write at once, consider setting it so an average batch would be ~ tens of KBs
- write() None [source]¶
Write logs from the queue to the stream.
This method is executed in a separate thread.
- close() None [source]¶
Close the handler including all connections to its destination.
This method is called automatically at exit for each added handler by the
clear()
function.
- classmethod accepts_destination(route: str, /) bool ¶
- abstract classmethod resolve_destination(route: str, /) str ¶
Resolve destination route and normalize it.
- set_level(level: Literal['NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL', 'NEVER'], /) None ¶
- route_prefix: ClassVar[str]¶
- class QueueStreamHandler[source]¶
Logging handler with an internal queue.
This handler uses a queue and a separate thread providing at least some concurrency during intensive logging workload. It has a worse overall performance than
StreamHandler
but may be beneficial if you have concurrent code such as a server application.You may want to set
queue_size
to some reasonable value considering your application workload.- classmethod accepts_destination(route: str, /) bool ¶
- close() None ¶
Close the handler including all connections to its destination.
This method is called automatically at exit for each added handler by the
clear()
function.
- classmethod resolve_destination(route: str, /) str ¶
Resolve destination route and normalize it.
- route_prefix: ClassVar = 'file'¶
- set_level(level: Literal['NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL', 'NEVER'], /) None ¶
- terminator: ClassVar = b'\n'¶
- write() None ¶
Write logs from the queue to the stream.
This method is executed in a separate thread.
- queue_size: int¶
Log queue size, infinite by default
- batch_size: int¶
Maximum number of log records to concatenate and write at once, consider setting it so an average batch would be ~ tens of KBs
- class StreamHandler[source]¶
Logging handler.
A simple stream handler which immediately writes a log record to the write buffer. It provides the best performance. However, in server applications you may want to use uvlog.QueueStreamLogger to ensure your code is not blocking due to intensive logging.
- terminator: ClassVar = b'\n'¶
- route_prefix: ClassVar = 'file'¶
- classmethod resolve_destination(route: str, /) str [source]¶
Resolve destination route and normalize it.
- close() None [source]¶
Close the handler including all connections to its destination.
This method is called automatically at exit for each added handler by the
clear()
function.
- set_level(level: Literal['NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL', 'NEVER'], /) None ¶
Formatters¶
- class Formatter[source]¶
Log formatter interface.
It’s a protocol class, i.e. one doesn’t need to inherit from it to create a valid formatter.
- class TextFormatter[source]¶
Text log formatter.
Creates human-readable log output.
Formatter settings must be set directly or using the
uvlog.config()
method._formatter = TextFormatter() _formatter.timespec = 'seconds'
- timespec: str¶
Precision for ISO timestamps, see datetime.isoformat()
- timestamp_separator: str¶
Timestamp separator for ISO timestamps, see datetime.isoformat()
- class JSONFormatter[source]¶
JSON log formatter.
To change the default dumps function assign it to the class attribute.
import orjson JSONFormatter.serializer = orjson.dumps
Formatter settings must be set directly or using the
uvlog.config()
method._formatter = JSONFormatter() _formatter.exc_pass_locals = True
- serializer() bytes ¶
Serializer function - a class attribute
- exc_pass_locals: bool¶
Pass locals dict in exception traceback (don’t use it unless your logs are secure)
- exc_pass_filenames: bool¶
Pass globals dict in exception traceback (don’t use it unless your logs are secure)
Variables¶
- uvlog.LOG_CONTEXT : ContextVar[dict[str, Any]] - Default log context variable¶
- uvlog.BASIC_CONFIG : dict - Default log configuration with stdout and stderr text handlers¶