Logz.io Python Handler

4.1.9 · active · verified Sun Apr 12

The `logzio-python-handler` library provides a Python logging handler that sends application logs to a Logz.io account. It supports bulk sending over HTTPS with SSL, handling logs asynchronously in a background thread, and offers optional OpenTelemetry trace context integration. As of version `4.1.9`, the library is actively maintained with frequent updates, primarily focusing on dependency management and robustness improvements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure the `LogzioHandler` with Python's standard `logging` module. It uses environment variables for the Logz.io token and log type, falling back to a console logger if the token isn't set. It shows how to log informational, warning, and exception messages.

import logging
import os
from logzio.handler import LogzioHandler

# Replace with your Logz.io token and log type
LOGZIO_TOKEN = os.environ.get('LOGZIO_TOKEN', 'YOUR_LOGZIO_TOKEN')
LOGZIO_TYPE = os.environ.get('LOGZIO_TYPE', 'python-application')

if LOGZIO_TOKEN == 'YOUR_LOGZIO_TOKEN':
    print("WARNING: Please set the LOGZIO_TOKEN environment variable or replace 'YOUR_LOGZIO_TOKEN' in the script.")
    print("Skipping Logz.io handler configuration for quickstart.")
    # Fallback to console logging if token is not set
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)
else:
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)

    try:
        handler = LogzioHandler(
            LOGZIO_TOKEN,
            logzio_type=LOGZIO_TYPE
            # url="https://listener.logz.io:8071" # Default, uncomment to specify a different listener URL
            # debug=True # Uncomment for debug output to stdout
        )
        logger.addHandler(handler)
        print(f"Logz.io handler configured for type: {LOGZIO_TYPE}")
    except Exception as e:
        print(f"Error configuring Logz.io handler: {e}")
        print("Falling back to console logging.")
        logging.basicConfig(level=logging.INFO)
        logger = logging.getLogger(__name__)

logger.info("This is an informational message sent via Logz.io handler.")
logger.warning("This is a warning message.")
try:
    1 / 0
except ZeroDivisionError:
    logger.exception("An error occurred during division. Full stack trace will be sent.")

# In a real application, the handler manages a background thread for sending logs.
# For simple scripts, a short delay might be needed to ensure logs are sent
# before the script exits, though graceful shutdown attempts to drain remaining logs.
import time
time.sleep(1) # Give the handler a moment to flush logs for short scripts

view raw JSON →