Logtail Python Client
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
- gotcha Starting from v0.3.3, the `host` parameter for `LogtailHandler` should *not* include the protocol (e.g., `https://`). If you were previously passing `https://in.logtail.com`, you should now pass `in.logtail.com` to avoid potential issues or misconfigurations.
- gotcha When shutting down your application, using `os._exit()` will terminate all threads immediately, which can result in unsent logs. For graceful termination and to ensure all buffered logs are sent to Logtail, use `sys.exit()` instead.
- gotcha Avoid configuring logging directly on the root logger (`logging.getLogger()`) in production applications. It can lead to less control and unexpected log destinations. Instead, get a named logger (`logging.getLogger(__name__)`) and add your `LogtailHandler` to it.
- gotcha While the library attempts to handle circular references in log records (improved in v0.2.10, v0.3.1, v0.3.2), passing extremely complex or deeply nested objects in `extra` data might still lead to serialization issues or performance overhead. Ensure that extra data is generally JSON-serializable.
Install
-
pip install logtail-python
Imports
- LogtailHandler
from logtail import LogtailHandler
Quickstart
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.")