API Reference

GLib → Python

class glib_log_bridge.glib2python.GLibToPythonLogger(logger_prefix='', logger_suffix='', use_priority_field=False)[source]

Class that contains the state (and methods) used to accept logs from GLib and forward them to the python logging system.

You need to pass the GLibToPythonLogger.glibToPythonLogWriterFunc() to the GLib.log_set_writer_func(). The “user data” is ignored, but subclasses can take advantage of that if they somehow want to.

Example usage:

>>> g2plog = glib2python.GLibToPythonLogger()
>>> GLib.log_set_writer_func(g2plog.glibToPythonLogWriterFunc, None)

You can create a subclass and overwrite the private methods if you need more control.

Parameters
__init__(logger_prefix='', logger_suffix='', use_priority_field=False)[source]

Initialize itself by just setting the attributes.

Parameters
_fields_to_dict(logfields)[source]

Converts a list of GLib.LogField to a python dictionary.

For fields whose length is -1 this is being treated as a UTF-8 strings, but if any error occur they’ll be in a bytes-object.

For other fields it’ll always be a bytes object. Note that when the GLib.LogField.value or GLib.LogField.length is 0, an empty bytes object is being used.

Parameters

logfields (List[LogField]) – The fields to convert from

Return type

Dict[str, Any]

Returns

An dictionary of the converted fields

_get_code_location(fields)[source]

Returns an tuple describing the code location.

Parameters

fields (Dict[str, Any]) – The fields to make the decision from.

Return type

Tuple[Optional[str], int, Optional[str]]

_get_log_level(fields, log_level, default=20)[source]

Converts the log level from the fields (or the GLib passed one) to an log level appropiate for Pythons logging system.

Parameters
  • fields (dict) – The fields to make the decision from.

  • log_level (LogLevelFlags) – GLib log level passed by GLib to the callback.

  • default – What to use whenever it couldn’t figure out.

Return type

int

Returns

The log level to use for Pythons logging.

_get_logger(fields)[source]

Returns the appropiate logger.

Parameters

fields (Dict[str, Any]) – The fields to make the decision from.

Return type

Logger

Returns

The logger to use to log to it.

_get_logger_name(fields)[source]

Returns the appropiate logger name from the fields. By default this uses (and converts) the GLIB_DOMAIN field.

The default implementation also uses GLibToPythonLogger.logger_prefix and GLibToPythonLogger.logger_suffix.

Parameters

fields (Dict[str, Any]) – The fields to make the decision from.

Return type

str

Returns

The name of the logger to use.

_get_message(fields)[source]

Returns the message to be passed to the logger. By default this uses the MESSAGE field. For non-string MESSAGE, it’ll call str() on it, except for a bytes object, where it will bytes.decode() it into a string, and replace invalid characters.

Parameters

fields (Dict[str, Union[str, bytes]]) – The fields to extract the code location info from.

Return type

str

Returns

The code path(/module name), line and function name.

_get_record(log_level, fields, user_data)[source]

Converts from the fields into an logging.LogRecord ready to be submitted to Pythons logging system.

The default implementation also inserts the original fields dictionary as the glib_fields attribute on the resulting logging.LogRecord.

Parameters
  • log_level (LogLevelFlags) – GLib log level passed by GLib to the callback.

  • fields (Dict[str, Any]) – The fields to make the decision from.

  • user_data – User data passed by GLib callback, specified when setting up the writer on the GLib side.

Return type

LogRecord

_glib_level_map: Dict[gi.repository.GLib.LogLevelFlags, int] = {gi.repository.GLib.LogLevelFlags.LEVEL_ERROR: 40, gi.repository.GLib.LogLevelFlags.LEVEL_CRITICAL: 50, gi.repository.GLib.LogLevelFlags.LEVEL_WARNING: 30, gi.repository.GLib.LogLevelFlags.LEVEL_MESSAGE: 20, gi.repository.GLib.LogLevelFlags.LEVEL_INFO: 20, gi.repository.GLib.LogLevelFlags.LEVEL_DEBUG: 10}

Maps from GLibs logging levels to python logging levels.

_log_level_priority_map: Dict[str, int] = {'0': 50, '1': 30, '2': 50, '3': 40, '4': 50, '5': 20, '6': 20, '7': 10}

Maps from journald’s PRIORITY=-field to pythons default logging levels.

glibToPythonLogFunc(log_domain, log_level, message, user_data)[source]

The function GLib should call handling an entry the unstructured way. Pass this to GLib.log_set_handler(). Note that the default handler forwards to the structured version when one isn’t registered, so please use glibToPythonLogWriterFunc() instead. Example:

GLib.log_set_handler("domain", GLib.LogLevelFlags.LEVEL_WARNING,
                     obj.glibToPythonLogFunc, None)

WARNING: Not tested yet.

Parameters
  • log_domain (str) – In what domain it was logged to.

  • log_level (LogLevelFlags) – What log level is being used.

  • message (str) – The message logged.

  • user_data (Optional[Any]) – Additional data, specified when setting up the writer on the GLib side. Not used in the default implementation.

Returns

Nothing that should be used, since it is a void.

glibToPythonLogWriterFunc(log_level, logfields, logfields_n, user_data)[source]

The function GLib should call when writing. Pass this to GLib.log_set_writer_func(), which is used when doing structured logging. Example:

GLib.log_set_writer_func(obj.glibToPythonLogWriterFunc, None)
Parameters
  • log_level (LogLevelFlags) – GLib version of the log level.

  • logfields (Union[List[LogField], Dict[str, Any]]) – Fields that the logger has. Can also directly be an converted dictionary, when you need to directly call it for some reason.

  • logfields_n (int) – Number of fields, same as len(logfields).

  • user_data (Optional[Any]) – Additional data, specified when setting up the writer on the GLib side. Not used in the default implementation.

Return type

LogWriterOutput

Returns

Whenever it handled successfully. In case of an exception, it’ll return as being unhandled.

logger_prefix: str = ''

What it should put before the converted logger name.

logger_suffix: str = ''

What it should put after the converted logger name.

use_priority_field: bool = False

Force using the journald PRIORITY=-field rather than the log level GLib passes directly.

Python → GLib

class glib_log_bridge.python2glib.PythonToGLibLoggerHandler(level=0, replace_module_char='-', log_domain_prefix='', log_domain_suffix='')[source]

Python logger handle that just forwards message records to the GLib logger.

Note that since this subclasses logging.Handler, view their documentation for more information, such as filters and so on.

Parameters
__init__(level=0, replace_module_char='-', log_domain_prefix='', log_domain_suffix='')[source]

Initializes the instance, basically setting the formatter to None and the filter list to empty.

Parameters
_convert_fields_dict(fields)[source]

Modifies a dictionary of the fields to convert their values into GLib Variants, ready to be passed into GLib.log_variant().

By default, existing GLib.Variant objects are untouched, strings are converted to Glib.Variant strings, and bytes objects to Glib.Variant bytes, as per the official documentation.

For other objects str() is called and the resulting string is inserted.

Note that strings containing an null-byte will be cut off for that point. An warning will be emitted in that case.

Parameters

fields (Dict[str, Any]) – The fields to convert.

Return type

Dict[str, Variant]

Returns

fields, which has been modified to be converted to GLib.Variant.

_get_fields(record, **kwargs)[source]

Return fields to use based on the given log record.

The default implementation will insert the following keys:

  • MESSAGE: The formatted message

  • CODE_FUNC, CODE_FILE, CODE_LINE: Where it logged

  • PYTHON_MESSAGE: The unformatted message

  • PYTHON_MODULE: What module the log was emitted from

  • PYTHON_LOGGER: To what logger name it was supposed to log to

  • PYTHON_TNAME: Thread Name

  • PYTHON_TID: Thread ID

The default implementaion will also insert exception information:

  • PYTHON_EXC: Exception type with complete name

  • PYTHON_EXC_MESSAGE: Stringify exception message

Additionally, the default implementation will also insert (and override) values from the glib_fields attribute of the record, if it exists and is a dict, when update_from_record is True (the default).

Subclasses can override this function to insert their own values and such.

Parameters
  • record (LogRecord) – The record to convert into a suitable dict.

  • update_from_record (bool) – Extend it with record.glib_fields, when it exists and is a dict. Defaults to True.

Return type

Dict[str, Any]

Returns

Converted dict from the specified record.

_get_log_domain(record)[source]

Returns the log domain for the specified record. The default implementation takes PythonToGLibLoggerHandler.log_domain_prefix and PythonToGLibLoggerHandler.log_domain_prefix into consideration.

Parameters

record (LogRecord) – The record to retrieve (and convert) the log domain from.

Return type

str

Returns

The log domain name to use to log to GLib.

_level_to_glib(level, default=gi.repository.GLib.LogLevelFlags.LEVEL_DEBUG)[source]

Converts a Python loglevel to a GLib log level. If no mapping exists, use the specified default value.

The default implementation will use the PythonToGLibLoggerHandler._level_to_glib_map map.

Parameters
  • level (int) –

  • default (LogLevelFlags) –

Return type

LogLevelFlags

_level_to_glib_map: Dict[int, gi.repository.GLib.LogLevelFlags] = {10: gi.repository.GLib.LogLevelFlags.LEVEL_DEBUG, 20: gi.repository.GLib.LogLevelFlags.LEVEL_INFO, 30: gi.repository.GLib.LogLevelFlags.LEVEL_WARNING, 40: gi.repository.GLib.LogLevelFlags.LEVEL_WARNING, 50: gi.repository.GLib.LogLevelFlags.LEVEL_WARNING}

Map used to convert from a Python logger level to the GLib Log Level.

emit(record)[source]

Log the specified record, by converting and forwarding it to the GLib logging system.

Normally, you wouldn’t use this directly but rather implicitly via Pythons logging system.

Parameters

record (LogRecord) – The record to log to GLib.

log_domain_prefix: str = ''

What it should put before the converted logger name.

log_domain_suffix: str = ''

What it should put after the converted logger name.

replace_module_char: str = '-'

What to replace the dots (logger namespace separator) with when converting.

class glib_log_bridge.python2glib.PythonToGLibWriterHandler(writer, user_data=None, level=0, **kwargs)[source]

Python logger handler that directly forwards to an GLib logger writer function. Example:

obj = PythonToGLibWriterHandler(GLib.log_writer_default)

Note that there are pre-existing instances at:

Note that since this subclasses logging.Handler, view their documentation for more information, such as filters and so on.

Parameters
__init__(writer, user_data=None, level=0, **kwargs)[source]

Initializes the instance, basically setting the formatter to None and the filter list to empty.

Parameters
  • writer (Callable[[LogLevelFlags, LogField, Any], LogWriterOutput]) – The writer function to forward to.

  • user_data (Optional[Any]) – Additional data to forward to the writer function.

_convert_fields(fields)[source]

Convert a record fields to an list of GLib.LogField.

Parameters

fields (Dict[str, Any]) – The fields to convert.

Return type

List[LogField]

Returns

The converted fields.

_get_fields(record, **kwargs)[source]

Return fields to use based on the given log record.

See PythonToGLibLoggerHandler._get_fields() for more information.

This implementation will also set GLIB_DOMAIN when not set.

Parameters
  • record (LogRecord) – The record to convert into a suitable dict.

  • update_from_record (bool) – Extend it with record.glib_fields, when it exists and is a dict. Defaults to True.

Return type

Dict[str, Any]

Returns

Converted dict from the specified record.

_get_logfields(record)[source]

Returns the GLib.LogField to pass to GLib for the specified record.

Parameters

record (LogRecord) – The record to convert from.

Return type

List[LogField]

Returns

The fields to pass to GLib.

emit(record)[source]

Log the specified record, by converting and forwarding it to the specified GLib Log Writer Function.

Normally, you wouldn’t use this directly but rather implicitly via Pythons logging system.

Parameters

record – The record to forward to GLib.

glib_log_bridge.python2glib.pythonToGLibWriterDefault = <PythonToGLibWriterHandler (NOTSET)>

Python Logger Handler to forward to GLib.log_writer_default().

glib_log_bridge.python2glib.pythonToGLibWriterJournald = <PythonToGLibWriterHandler (NOTSET)>

Python Logger Handler to forward to GLib.log_writer_journald().

glib_log_bridge.python2glib.pythonToGLibWriterStandardStreams = <PythonToGLibWriterHandler (NOTSET)>

Python Logger Handler to forward to GLib.log_writer_standard_streams().