Skip to main content

GELF formatter for the Python standard library logging module.

Project description

GELF Formatter

Graylog Extended Log Format (GELF) formatter for the
Python standard library logging module

PyPI Python versions CI License


Motivation

There are several packages available providing handlers for the standard library logging module that can send application logs to Graylog by TCP/UDP/HTTP (py-gelf is a good example). Although these can be useful, it's not ideal to make an application performance dependent on network requests just for the purpose of delivering logs.

Alternatively, one can simply log to a file or stdout and have a collector (like Fluentd) processing and sending those logs asynchronously to a remote server (and not just to Graylog, as GELF can be used as a generic log format), which is a common pattern for containerized applications. In a scenario like this all we need is a GELF logging formatter.

Features

  • Support for arbitrary additional fields
  • Support for including reserved logging.LogRecord attributes as additional fields
  • Exceptions detection with traceback formatting
  • Full type annotations (PEP 561 compatible)
  • Zero dependencies and tiny footprint

Installation

pip install gelf-formatter

Usage

Create a GelfFormatter instance and pass it to logging.Handler.setFormatter:

import sys
import logging

from gelfformatter import GelfFormatter

formatter = GelfFormatter()

handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)

Apply it globally with logging.basicConfig to automatically format log records from third-party packages as well:

logging.basicConfig(level=logging.DEBUG, handlers=[handler])

Alternatively, configure a local logging.Logger instance through logging.Logger.addHandler:

logger = logging.getLogger('my-app')
logger.addHandler(handler)

That's it. You can now use the logging module as usual, all records will be formatted as GELF messages.

Standard Fields

The formatter outputs all (non-deprecated) fields described in the GELF Payload Specification (version 1.1):

  • version: String, always set to 1.1
  • host: String, the output of socket.gethostname at initialization
  • short_message: String, log record message
  • full_message (optional): String, formatted exception traceback (if any)
  • timestamp: Number, time in seconds since the epoch as a floating point
  • level: Integer, syslog severity level

None of these fields can be ignored, renamed or overridden.

Example

logging.info("Some message")
{"version":"1.1","host":"my-server","short_message":"Some message","timestamp":1557342545.1067393,"level":6}

Exceptions

The full_message field is used to store the traceback of exceptions. Log them with logging.exception.

import urllib.request

req = urllib.request.Request('http://www.pythonnn.org')
try:
    urllib.request.urlopen(req)
except urllib.error.URLError as e:
    logging.exception(e.reason)
{"version": "1.1", "short_message": "[Errno -2] Name or service not known", "timestamp": 1557342714.0695107, "level": 3, "host": "my-server", "full_message": "Traceback (most recent call last):\n  ...(truncated)... raise URLError(err)\nurllib.error.URLError: <urlopen error [Errno -2] Name or service not known>"}

Additional Fields

The GELF specification allows arbitrary additional fields, with keys prefixed with an underscore.

To include additional fields use the standard logging extra keyword. Keys will be automatically prefixed with an underscore (if not already).

logging.info("request received", extra={"path": "/orders/1", "method": "GET"})
{"version": "1.1", "short_message": "request received", "timestamp": 1557343604.5892842, "level": 6, "host": "my-server", "_path": "/orders/1", "_method": "GET"}

Reserved Fields

By default the formatter ignores all logging.LogRecord attributes. You can opt to include them as additional fields using allowed_reserved_attrs:

formatter = GelfFormatter(allowed_reserved_attrs=["lineno", "module", "filename"])

logging.debug("starting application...")
{"version": "1.1", "short_message": "starting application...", "timestamp": 1557346554.989846, "level": 6, "host": "my-server", "_lineno": 175, "_module": "myapp", "_filename": "app.py"}

Similarly, you can ignore additional attributes passed via extra using ignored_attrs:

formatter = GelfFormatter(ignored_attrs=["secret", "password"])

logging.debug("app config", extra={"connection": "local", "secret": "verySecret!"})
{"version": "1.1", "short_message": "app config", "timestamp": 1557346554.989846, "level": 6, "host": "my-server", "_connection": "local"}

Note: Only root-level keys are filtered. Nested fields within objects are not filtered.

Context Fields

Use a logging.Filter to add context fields to all log messages:

class ContextFilter(logging.Filter):
    def filter(self, record):
        record.app = "my-app"
        record.environment = os.environ.get("APP_ENV")
        return True

handler.addFilter(ContextFilter())

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

gelf_formatter-1.0.0.tar.gz (7.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

gelf_formatter-1.0.0-py3-none-any.whl (7.3 kB view details)

Uploaded Python 3

File details

Details for the file gelf_formatter-1.0.0.tar.gz.

File metadata

  • Download URL: gelf_formatter-1.0.0.tar.gz
  • Upload date:
  • Size: 7.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for gelf_formatter-1.0.0.tar.gz
Algorithm Hash digest
SHA256 682a9f9c6e8dc7c8f56d0ad3c072528d54feaab36cf31e884150d90b91d8d442
MD5 bfaea79fde6cec2ddd3fbfd00c3cbcdf
BLAKE2b-256 73b0dd3188761b5db2e7efeccc8ea269c6678f263abb9104003cc11b79da7a4c

See more details on using hashes here.

Provenance

The following attestation bundles were made for gelf_formatter-1.0.0.tar.gz:

Publisher: publish.yml on joaodrp/gelf-formatter

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file gelf_formatter-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: gelf_formatter-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 7.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for gelf_formatter-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2ad0e42bf334a4a18d17fe70adae90eb550c28657d5dbd5a9caaabc2262d4404
MD5 0e7774ad4e126506f43e8f33716916cf
BLAKE2b-256 27066dbc9264cc7f010198c989acd65ddeba0f2c36a6c451a9ee7227b93e0820

See more details on using hashes here.

Provenance

The following attestation bundles were made for gelf_formatter-1.0.0-py3-none-any.whl:

Publisher: publish.yml on joaodrp/gelf-formatter

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page