GELF Logging Handler

0.4.3 · active · verified Thu Apr 16

pygelf provides logging handlers for the GELF (Graylog Extended Log Format) specification, allowing Python applications to send logs to Graylog servers or other GELF-compatible log management systems. It supports UDP, TCP, and HTTP transport protocols, including features like compression and chunking for large messages. The current version is 0.4.3, and it receives active maintenance with a moderate release cadence.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure a Python logger with `GELFUDPHandler` to send log messages to a Graylog instance. It shows basic info, warning, and exception logging, including how to pass extra fields to GELF. Remember to replace placeholder host/port or set them via environment variables to match your Graylog setup.

import logging
import os
from pygelf import GELFUDPHandler

# Replace with your Graylog host and port, or set as environment variables
GRAYLOG_HOST = os.environ.get('GRAYLOG_HOST', '127.0.0.1')
GRAYLOG_PORT = int(os.environ.get('GRAYLOG_PORT', '12201')) # Default GELF UDP port

logger = logging.getLogger('my_app')
logger.setLevel(logging.INFO)

# Configure GELF UDP handler
handler = GELFUDPHandler(
    host=GRAYLOG_HOST,
    port=GRAYLOG_PORT,
    _source_host='my_python_app', # Custom field example
    include_extra_fields=True # Include extra dict fields in log record
)
logger.addHandler(handler)

# Example log messages
logger.info("This is an informational message.")
logger.warning("A warning occurred!", extra={'user_id': 123, 'transaction_id': 'abc-xyz'})
try:
    1 / 0
except ZeroDivisionError:
    logger.exception("An error occurred during division.")

print(f"Logs sent to {GRAYLOG_HOST}:{GRAYLOG_PORT}. Check your Graylog instance.")

view raw JSON →