logging_gelf.formatters — Formatters

class logging_gelf.formatters.GELFFormatter

A subclass of logging.Formatter to format LogRecord into GELF.

__init__(schema=<logging_gelf.schemas.GelfSchema>, null_character=False, JSONEncoder=json.JSONEncoder, exclude_patterns=None)

A GELF formatter to format a logging.LogRecord into GELF.

  • schema (logging_gelf.schemas.GelfSchema) – The marshmallow schema to use to format data.
  • null_character (bool) – Append a ‘0’ at the end of the string. It depends on the input used.
  • JSONEncoder (json.JSONEncoder) – A custom json encoder to use.
  • exclude_patterns (list|None) – List of regexp used to exclude keys

New in version 0.0.12: The exclude_patterns parameter.


Format the specified record into json using the schema which MUST inherit from logging_gelf.schemas.GelfSchema.

Parameters:record (logging.LogRecord) – Contains all the information pertinent to the event being logged. :return: A JSON dump of the record. :rtype: str

Filter GELF record keys using exclude_patterns

Parameters:data (dict) – Log record has dict :return: the filtered log record :rtype: dict

New in version 0.0.12.

Testing the output

You can use the logging.StreamHandler to test your formatter:

>>> import sys
>>> import logging
>>> from logging_gelf.formatters import GELFFormatter

# we create the logger
>>> logger = logging.getLogger("gelf")
>>> logger.setLevel(logging.DEBUG)

# we use StreamHandler to display the result
>>> handler = logging.StreamHandler(sys.stdout)
>>> handler.setFormatter(GELFFormatter())
>>> logger.addHandler(handler)

# we send a log entry
>>> logger.debug("hello !")
{"version": "1.1", "host": "host.example.com", "file": "<stdin>", "short_message": "hello !", "timestamp": 1484820522.4268215, "level": 7, "line": 1}

The next example uses marshmallow and a custom JSONEncoder which transform all list, tuple or dict to strings:

>>> import logging
>>> import sys
>>> from logging_gelf.formatters import GELFFormatter, StringJSONEncoder
>>> from marshmallow import fields, Schema
>>> from logging_gelf.schemas import GelfSchema
>>> class Person(GelfSchema):
...     lastname = fields.String()
...     father = fields.Nested(Person)
...     firstname = fields.List(fields.String)
>>> me = dict(lastname="Dumay", firstname=["Cedric", "Julien"])
>>> logger = logging.getLogger("gelf")
>>> logger.setLevel(logging.DEBUG)
>>> handler = logging.StreamHandler(sys.stdout)
>>> handler.setFormatter(
...     GELFFormatter(schema=Person, JSONEncoder=StringJSONEncoder))
>>> logger.addHandler(handler)
>>> logger.debug("A marshmallow example with Nested", extra=me)
{"host": "host.example.com", "_firstname": "['Cedric', 'Julien']", "file": "<stdin>", "version": "1.1", "short_message": "A marshmallow example with Nested", "timestamp": 1486643773.3877068, "level": 7, "line": 1, "_lastname": "Dumay"}

As we can see, firstname is not an array.

See also

Formatter Objects
Official python documentation