Logtail Python Client

0.3.4 · active · verified Tue Apr 14

Logtail-python is the official Python client library for Logtail.com (part of Better Stack). It provides a `logging.Handler` to easily send logs from your Python applications, including Django and FastAPI, to Logtail for centralized log management, aggregation, and analysis. It is actively maintained with frequent updates, currently at version 0.3.4.

Warnings

Install

Imports

Quickstart

This quickstart sets up a basic Python logger with `LogtailHandler` to send logs to Logtail. It demonstrates logging INFO, WARNING, and an exception with extra structured data. Remember to replace `YOUR_LOGTAIL_SOURCE_TOKEN` with your actual token or set `LOGTAIL_SOURCE_TOKEN` as an environment variable, and verify your `INGESTING_HOST` if not using the default.

import logging
import os
from logtail import LogtailHandler

# Ensure SOURCE_TOKEN is set in your environment variables
# or replace with your actual source token for testing.
SOURCE_TOKEN = os.environ.get('LOGTAIL_SOURCE_TOKEN', 'YOUR_LOGTAIL_SOURCE_TOKEN')
INGESTING_HOST = os.environ.get('LOGTAIL_INGESTING_HOST', 'in.logtail.com') # Default host, may vary by region/setup

handler = LogtailHandler(
    source_token=SOURCE_TOKEN,
    host=INGESTING_HOST
)

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# Clear existing handlers to prevent duplicate logs if running multiple times
# or if root logger already has handlers. Optional, but good practice.
logger.handlers = []
logger.addHandler(handler)

logger.info('Hello from Logtail-python!', extra={'service': 'my-app', 'environment': 'development'})
logger.warning('This is a warning message.', extra={'user_id': 123})

try:
    1 / 0
except ZeroDivisionError:
    logger.exception('An error occurred during division.')

print("Logs sent to Logtail (check your Logtail Live tail). If nothing appears, ensure your SOURCE_TOKEN and INGESTING_HOST are correct.")

view raw JSON →