graypy
graypy is a Python library that provides logging handlers for sending messages in the Graylog Extended Log Format (GELF). It integrates with Python's standard `logging` module and supports various transport protocols including UDP, TCP, TLS, HTTP, and RabbitMQ. The current version is 2.1.0, and while there isn't a strict release cadence, major versions have introduced breaking changes.
Warnings
- breaking The `GELFHandler` and `GELFTcpHandler` classes were removed in `graypy` version 1.x.x. Users migrating from 0.x.x to 1.x.x or newer must update their code to use `GELFUDPHandler`, `GELFTCPHandler`, or `GELFTLSHandler` respectively.
- gotcha `GELFUDPHandler` sends logs via UDP, which is a connectionless protocol and does not guarantee message delivery. Critical logs that must not be lost should be sent via `GELFTCPHandler`, `GELFTLSHandler`, `GELFHTTPHandler`, or `GELFRabbitHandler` for more reliable transport.
- gotcha When using `GELFRabbitHandler`, you must manually configure RabbitMQ with a GELF-compatible queue and bind it to a logging exchange. Graylog then consumes messages from this AMQP queue.
- gotcha There is no formal changelog maintained for `graypy` on GitHub, which can make it challenging to track specific changes, new features, or breaking alterations between versions.
- gotcha When deploying `graypy` in containerized environments (e.g., with Docker or Kubernetes, especially with Django applications), ensure that the application container and the Graylog container are on the same network and configured with correct hostnames or IP addresses for communication.
Install
-
pip install graypy
Imports
- GELFUDPHandler
from graypy import GELFUDPHandler
- GELFTCPHandler
from graypy import GELFTCPHandler
- GELFTLSHandler
from graypy import GELFTLSHandler
- GELFHTTPHandler
from graypy import GELFHTTPHandler
- GELFRabbitHandler
from graypy import GELFRabbitHandler
- GELFHandler
from graypy import GELFUDPHandler
- GELFTcpHandler
from graypy import GELFTCPHandler
Quickstart
import logging
import graypy
import os
# Configure Graylog host and port, using environment variables for security
GRAYLOG_HOST = os.environ.get('GRAYLOG_HOST', 'localhost')
GRAYLOG_PORT = int(os.environ.get('GRAYLOG_PORT', 12201))
# Get a logger instance
my_logger = logging.getLogger('my_app_logger')
my_logger.setLevel(logging.DEBUG)
# Create a GELF UDP handler
handler = graypy.GELFUDPHandler(GRAYLOG_HOST, GRAYLOG_PORT)
my_logger.addHandler(handler)
# Send a log message
my_logger.debug('Hello Graylog from graypy!')
my_logger.info('This is an informational message.')
my_logger.warning('Something might be wrong here.')
try:
1 / 0
except ZeroDivisionError:
my_logger.exception('An error occurred!')
print(f"Log messages sent to Graylog at {GRAYLOG_HOST}:{GRAYLOG_PORT} (UDP).")