The Burin Module

Overview

Within Burin everything needed for normal usage is available on the top-level burin module. There is typically no need to import any other packages or modules from within Burin.

Formatters, Handlers, Loggers and Logger Adapters, and Filters and Filterers are all documented in their own sections. This page will focus on the Constants, Config Attributes, and Functions that are available directly on the burin module.

Constants

The logging levels are integer values that correspond to a kind of seriousness of a logging event; with higher values being more serious.

Whenever you need to pass a logging level these values can be used directly such as burin.DEBUG, as string representations like "DEBUG", or as straight integer values.

Note

Burin does not currently support customisation or adding of your own log levels. This is planned to be added in a future release.

burin.CRITICAL = 50
burin.ERROR = 40
burin.WARNING = 30
burin.INFO = 20
burin.DEBUG = 10
burin.NOTSET = 0

Config Attributes

There are a handful of attributes that control some aspects of logging. These can be configured through the burin.config object.

Most of these control whether some data is available for inclusion in logs or not.

Note

This differs slightly from logging where the attributes are directly on the module.

burin.config.logAsyncioTasks = True

Whether asyncio.Task names should be available for inclusion in logs. Whatever value is set for this will be automatically converted using bool().

Note

In Python 3.12 this was added to the standard logging module; it is supported here for all versions of Python compatible with Burin (including versions below 3.12).

However; names were added to asyncio.Task objects in Python 3.8, so in Python 3.7 the taskName attribute on a log record will always be None.

burin.config.logMultiprocessing = True

Whether multiprocessing info should be available for inclusion in logs. Whatever value is set for this will be automatically converted using bool().

burin.config.logProcesses = True

Whether process info should be available for inclusion in logs. Whatever value is set for this will be automatically converted using bool().

burin.config.logThreads = True

Whether threading info should be available for inclusion in logs. Whatever value is set for this will be automatically converted using bool().

burin.config.raiseExceptions = True

Whether exceptions during handling should be propagated or ignored. Whatever value is set for this will be automatically converted using bool().

Functions

There are many top-level functions within the Burin module. These provide ways to configure logging, get loggers, log directly, or add customised functionality.

Note

Many of these functions will have slight changes from the standard logging module due to added functionality.

In most use cases though calling any of these functions in the same way as the logging module should work exactly the same way.

Note

All of the functions with an underscore_separated name also have a camelCase alias name which matches the names used in the standard logging library.

Below is a summary list of all functions in the module; and then further below are the full details of the functions grouped into categories based on their general purpose.

basic_config

Does a basic configuration of the Burin root logger.

capture_warnings

Enables or disables capturing of warnings through logs instead.

critical

Logs a message with the CRITICAL level.

debug

Logs a message with the DEBUG level.

disable

Provides a way to easily disable a level for all loggers.

error

Logs a message with the ERROR level.

exception

Logs a message with the ERROR level and exception information.

get_handler_by_name

Gets a handler with the specified name.

get_handler_names

Gets all known handler names as an immutable set.

get_level_name

Return the textual or numeric representation of a logging level.

get_level_names_mapping

Gets the current log levels name to level mapping.

get_log_record_factory

Gets the log record factory class for the specified style.

get_logger

Get a logger with the specified name and msgStyle.

get_logger_class

Gets the class that is used when instantiating new loggers.

info

Logs a message with the INFO level.

log

Logs a message with the specified level.

make_log_record

Creates a new log record from a dictionary.

set_log_record_factory

Sets the log record class to use as a factory.

set_logger_class

Sets a class to be used when instantiating new loggers.

shutdown

Cleans up by flushing and closing all handlers.

warning

Logs a message with the WARNING level.

Configuration

These functions are used to configure the logging setup.

Note

Burin does not yet support functionality similar to the logging.config dictConfig, fileConfig, and listen functions. This is planned to be added in a future release.

burin.basic_config(*, datefmt=None, encoding=None, errors='backslashreplace', filedatefmt=None, filedelay=False, fileformat=None, filelevel=None, filemode='a', filename=None, filerotate=False, filerotatecount=4, filerotatesize=1048576, force=False, format=None, handlers=None, level='WARNING', msgstyle='%', stream=None, streamdatefmt=None, streamformat=None, streamlevel=None, style='%')

Does a basic configuration of the Burin root logger.

This function will configure handlers for the root logger. This is a convenience method intended to cover several common logging use cases.

Note

All arguments to this function are optional and must be passed as keyword arguments, no positional arguments are supported.

With this function a file handler (or rotating file hander) and stream handler can both be added to the root logger. An iterable of other handlers can also be added. This differs from the standard logging.basicConfig() where only one of these can be configured.

The file and stream handlers can each have a different format, datefmt, and level using the parameters prefixed with file or stream. The general format, datefmt, and level parameters are used if file or stream specific values are not set.

Any handler within handlers that does not have a formatter will have a formatter set for them using the general format and datefmt.

If the root logger already has handlers this function can still be used to add additional handlers, configure new file and/or stream handlers for the root logger, and change other settings of the root logger. This differs from the standard logging.basicConfig() where nothing would be done if the root logger already has handlers.

If handlers, filename, and stream are all None, and the root logger does not have any handlers then a stream handler using sys.stderr is created and added to the root logger. If these arguments are all None and the root logger does have handlers then the other configuration values are still applied if set (level and msgstyle).

Parameters:
  • datefmt (str) – The date/time format to use (as accepted by time.strftime()).

  • encoding (str) – If specified with a filename this is passed to the handler and used when the file is opened.

  • errors (str) – If specified with filename this is passed to the handler and used when the file is opened. (Default = ‘backslashreplace’)

  • filedatefmt (str) – The date/time format to use specifically for the file handler. If this is None than the general datefmt argument is used instead.

  • filedelay (bool) – Whether to delay opening the file until the first record is emitted. (Default = False)

  • fileformat (str) – The format string to use specifically for the file handler. If this is None than the general format argument is used instead.

  • filelevel – The level to set specifically for the file handler. If this is None then the general level argument is used instead.

  • filemode (str) – If specified with filename then this is the mode with which the file is opened. (Default = ‘a’)

  • filename (str | pathlib.Path) – Specifies that a file handler is to be created and the file path to write to.

  • filerotate (bool) – Whether a rotating file handler or normal file handler should be created. (Default = False)

  • filerotatecount (int) – If filerotate is True then this is how many extra log files should be kept after rotating. (Default = 4)

  • filerotatesize (int) – If filerotate is True then this sets the size of the log file in bytes before it should be rotated. (Default = 1048576 (1MB))

  • force (bool) – Whether all existing handlers on the root logger should be removed and closed. (Default = False)

  • format (str) – The format string to use for the handlers. If this is None then a default format string will be used that has the level, logger name, and message.

  • handlers (list[BurinHandler]) – This can be an iterable of handlers that were already created and should be added to the root logger. Any handler within that doesn’t have a formatter will have the general formatter assigned to it.

  • level (int | str) – The level to set on the root logger. You can set separate levels for the file and stream handlers by using the filelevel and streamlevel parameters. (Default = ‘WARNING’)

  • msgstyle (str) – This sets the style that is used for deferred formatting of log messages on the root logger. This will also change the default style for any new loggers created afterwards. Built in possible values are ‘%’ for %-formatting, ‘{’ for str.format() formatting, and ‘$’ for string.Template formatting. Other values can be used if custom log record factories are added using set_log_record_factory(). (Default = ‘%’)

  • stream (io.TextIOBase) – Specifies that a stream handler is to be created with the passed stream for output.

  • streamdatefmt (str) – The date/time format to use specifically for the stream handler. If this is None than the general datefmt argument is used instead.

  • streamformat (str) – The format string to use specifically for the stream handler. If this is None than the general format argument is used instead.

  • streamlevel (int) – The level to set specifically for the stream handler. If this is None then the general level argument is used instead.

  • style (str) – The type of formatting to use for the format strings. Possible values are ‘%’ for %-formatting, ‘{’ for str.format() formatting, and ‘$’ for string.Template formatting. (Default = ‘%’)

Raises:
  • ConfigError – If msgstyle does not match a type of log record factory.

  • FormatError – If there are errors with the format, fileformat, or streamformat strings or style.

Logging

These functions can be used directly to log messages with either the root logger or another logger by using the logger parameter to specify the name.

burin.critical(msg, *args, logger=None, **kwargs)

Logs a message with the CRITICAL level.

A specific logger can be used passing its name with the logger keyword argument; otherwise the root logger is used.

Additional arguments are interpreted the same way as log().

Parameters:
  • msg (str) – The message to log.

  • logger (str) – The name of the logger to log the event with.

burin.debug(msg, *args, logger=None, **kwargs)

Logs a message with the DEBUG level.

A specific logger can be used passing its name with the logger keyword argument; otherwise the root logger is used.

Additional arguments are interpreted the same way as log().

Parameters:
  • msg (str) – The message to log.

  • logger (str) – The name of the logger to log the event with.

burin.error(msg, *args, logger=None, **kwargs)

Logs a message with the ERROR level.

A specific logger can be used passing its name with the logger keyword argument; otherwise the root logger is used.

Additional arguments are interpreted the same way as log().

Parameters:
  • msg (str) – The message to log.

  • logger (str) – The name of the logger to log the event with.

burin.exception(msg, *args, exc_info=True, logger=None, **kwargs)

Logs a message with the ERROR level and exception information.

A specific logger can be used passing its name with the logger keyword argument; otherwise the root logger is used.

This should normally be called only within an exception handler.

Additional arguments are interpreted the same way as log().

Parameters:
  • msg (str) – The message to log.

  • logger (str) – The name of the logger to log the event with.

burin.info(msg, *args, logger=None, **kwargs)

Logs a message with the INFO level.

A specific logger can be used passing its name with the logger keyword argument; otherwise the root logger is used.

Additional arguments are interpreted the same way as log().

Parameters:
  • msg (str) – The message to log.

  • logger (str) – The name of the logger to log the event with.

burin.log(level, msg, *args, exc_info=None, extra=None, logger=None, stack_info=False, stacklevel=1, **kwargs)

Logs a message with the specified level.

Note

The arguments exc_info, extra, logger, stack_info, and stacklevel are all keyword only arguments. These cannot be passed as positional arguments.

A specific logger can be used passing its name with the logger keyword argument; otherwise the root logger is used.

Any additional args and kwargs will be kept with the message and used for deferred formatting before output. Deferred formatting allows you to pass in a format string for the message and the values as additional arguments. The message then will only be formatted if it is going to be emitted by a handler.

How this formatting is done is determined by the log record factory used. This is controlled by the BurinLogger.msgStyle property of the logger. See BurinLogger.log() for examples of the different msgStyle deferred formatting options.

Additional or customised log record factories can be used by adding them with the set_log_record_factory() function.

Parameters:
  • level (int | str) – The level to log the message at.

  • msg (str) – The message to log.

  • exc_info (Exception | tuple(type, Exception, traceback) | bool) – Exception information to be added to the logging message. This should be an exception instance or an exception tuple (as returned by sys.exc_info()) if possible; otherwise if it is any other value that doesn’t evaluate as False then the exception information will be fetched using sys.exc_info().

  • extra (dict{str: Any}) – A dictionary of extra attributes that are applied to the log record’s __dict__. These can be used to populate custom fields that you set in your format string for BurinFormatter. The keys in this dictionary must not interfere with the built in fields/keys in the log record.

  • logger (str) – The name of the logger to log the event with. By default and when this is None then the root logger is used. If this is not None and the named logger doesn’t exist then it is created first.

  • stack_info (bool) – Whether to get the stack information from the logging call and add it to the log record. This allows for getting stack information for logging without an exception needing to be raised. (Default = False)

  • stacklevel (int) – If this is greater than 1 then the corresponding number of stack frames are skipped back through when getting the logging caller’s information (like filename, lineno, and funcName). This can be useful when the log call was from helper/wrapper code that doesn’t need to be included in the log record.

Raises:

KeyError – If any key in extra conflicts with a built in key of the log record.

burin.warning(msg, *args, logger=None, **kwargs)

Logs a message with the WARNING level.

A specific logger can be used passing its name with the logger keyword argument; otherwise the root logger is used.

Additional arguments are interpreted the same way as log().

Parameters:
  • msg (str) – The message to log.

  • logger (str) – The name of the logger to log the event with.

Loggers

These are the top-level functions you can use to get logger instances or to customise the logger class used.

burin.get_logger(name=None, msgStyle=None)

Get a logger with the specified name and msgStyle.

If name is None then the root logger will be returned. Otherwise it will try to find any previously created logger with the specified name.

If no existing logger with name is found then a new BurinLogger instance is created with that name. When creating a new logger if msgStyle is None then the msgStyle of the root logger will be used.

A name can be any almost text value the developer likes. Any periods ‘.’ within the names though will be treated as separators for a hierarchy of loggers. For example a name of ‘a.b.c’ will get or create logger ‘a.b.c’ which is a child of logger ‘a.b’; logger ‘a.b’ is also a child of logger ‘a’. Any parts of the hierarchy that don’t exist already are constructed with placeholder classes that are replaced with actual loggers if ever fetched by name.

Children in the hierarchy typically propagate logging events up to parents which allows for handlers further up the hierarchy to emit these log records.

If msgStyle is not None then it will be set as the msgStyle on the retrieved logger. If this is the root logger then that will become the default msgStyle for all new loggers created afterwards.

Parameters:
  • name (str) – The name of the logger the get. If this logger doesn’t exist already then it will be created. If this is None then the root logger will be returned.

  • msgStyle – If this is not None then it is set as the msgStyle on the retrieved logger. If that is the root logger then this will also change the default msgStyle for any new loggers created afterwards. Built in possible values are ‘%’ for %-formatting, ‘{’ for str.format() formatting, and ‘$’ for string.Template formatting. Other values can be used if custom log record factories are added using set_log_record_factory().

Returns:

The logger with the specified name.

Return type:

BurinLogger

Raises:

FactoryError – If msgStyle doesn’t match any known log record factory.

burin.get_logger_class()

Gets the class that is used when instantiating new loggers.

Returns:

The class new loggers are created with.

Return type:

BurinLogger

burin.set_logger_class(newClass)

Sets a class to be used when instantiating new loggers.

The class being set must be derived from BurinLogger.

Parameters:

newClass (BurinLogger) – A new class to be used when instantiating new loggers. This must be a subclass of BurinLogger.

Raises:

TypeError – If the received class is not a subclass of BurinLogger.

Handlers

These are top-level functions that can be used to get handler names or a specific handler by name if a name has be set on the handler.

burin.get_handler_by_name(name)

Gets a handler with the specified name.

If no handler exists with the name then None is returned.

Parameters:

name (str) – The name of the handler to get.

Returns:

The handler with the specified name or None if it doesn’t exist.

Return type:

BurinHandler | None

burin.get_handler_names()

Gets all known handler names as an immutable set.

Returns:

A frozenset of the handler names.

Return type:

frozenset

Log Records

The log record classes are used to represent the log event values and format the passed log message before output. These are referred to as factories when logger instances create an instance of the record for an event.

The built-in log record factories provide different formatting options as demonstrated in Deferred Formatting Styles. However custom log record factories can also be added by using the set_log_record_factory(). An example of this is shown in Customisable Log Records.

burin.get_log_record_factory(msgStyle='%')

Gets the log record factory class for the specified style.

If no log record factory exists for the msgStyle then None is returned.

Parameters:

msgStyle (str) – The style to get the associated log record factory for. (Default = ‘%’)

Returns:

The log record factory class associated with the msgStyle or None if no factory exists for that style.

Return type:

BurinLogRecord | None

burin.make_log_record(recordDict, msgStyle='%')

Creates a new log record from a dictionary.

This is intended for rebuilding log records that were pickled and sent over a socket.

Typically msgStyle won’t matter here as the msg formatting is done before a record is pickled and sent. It is provided as a parameter here for special use cases.

Parameters:
  • recordDict (dict{str: Any}) – The dictionary of the log record attributes.

  • msgStyle (str) – The msgStyle of which log record factory to use when rebuilding the record. (Default = ‘%’)

Returns:

The reconstructed log record.

Return type:

BurinLogRecord

burin.set_log_record_factory(factory, msgStyle='%')

Sets the log record class to use as a factory.

The factory can be set to any type of msgStyle. If a factory is already set for that msgStyle it is replaced, otherwise the new factory is simply added without impacting the other factories.

Once a factory has been set to a msgStyle then the same style can be used as the msgStyle on loggers to use that specific log record factory.

Parameters:
  • factory (BurinLogRecord) – The new log record class to use as a factory. This should be a subclass of BurinLogRecord.

  • msgStyle (str) – The style and key used to reference the factory for loggers. (Default = ‘%’)

Log Levels

These functions are meant to help with some situations dealing with logging levels. For example disabling all logging of specific levels with one simple call, and providing a helper method that may be useful for some wrappers.

Note

Burin does not currently support customisation or adding of your own log levels. This is planned to be added in a future release.

burin.disable(level='CRITICAL')

Provides a way to easily disable a level for all loggers.

This can be helpful for situations where you need to throttle logging output throughout an entire application quickly.

All logging events of level or below will not be processed.

To reset this back to normal it can simply be called again with NOTSET as level.

Parameters:

level (int | str) – The level where all logging events and below should not be processed. (Default = “CRITICAL”)

burin.get_level_name(level)

Return the textual or numeric representation of a logging level.

If a numeric value corresponding to one of the defined levels (CRITICAL, ERROR, WARNING, INFO, DEBUG) is passed in, the corresponding string representation is returned.

If a string representation of the level is passed in, the corresponding numeric value is returned.

Note

Unlike the standard library logging.getLevelName() a lower case name can also be used; all level name checks are automatically converted to uppercase.

If no matching numeric or string value is passed in, the string f'Level {level}' level is returned.

Parameters:

level (int | str) – The logging level to get the text or numeric representation of.

Returns:

If level is an int then a string representation of the level is returned; otherwise, if level is a str then an integer representation of the level is returned.

Return type:

int | str

burin.get_level_names_mapping()

Gets the current log levels name to level mapping.

Note

In Python 3.11 logging.getLevelNamesMapping() was added to the standard library; it is supported here for all versions of Python compatible with Burin (including versions below 3.11).

Returns:

A dictionary of the current logging level names mapped to the level values.

Return type:

dict{str: int}

Warnings Integration

Like the Python standard logging package Burin also supports some integration with the warnings module.

burin.capture_warnings(capture)

Enables or disables capturing of warnings through logs instead.

When this is enabled warnings.showwarning() is overridden with a function that will automatically log all warnings that are called through warnings.showwarning().

Parameters:

capture (bool) – Enable or disabled capturing of warnings for log output.

Clean Up

Burin will handle cleaning up of all handlers automatically when the program exits, so there shouldn’t be any need for manual cleanup. However; if you want Burin to clean up handlers before then you can call the shutdown() function.

burin.shutdown(handlerList=None)

Cleans up by flushing and closing all handlers.

This is automatically registered with atexit.register() and therefore shouldn’t need to be called manually when an application closes.

Note

In Python 3.12 this was changed to check if a handler has a flushOnClose property set to False to prevent flushing during shutdown (targetting logging.MemoryHandler). This is supported here for all versions of Python compatible with Burin (including versions below 3.12). The check was also left generic so any custom handlers that may not want to flush when closed can benefit.

Parameters:

handlerList (list[BurinHandler]) – The handlers to be cleaned up. If this is None then it will default to an internal list of all Burin handlers. This should not need to be changed in almost all circumstances. However; if you only want to clean up a specific set of handlers then pass them here.