Skip to main content

SQLite log handler for Python logging module

Project description

Python SQLite Log Handler

build CodeQL PyPI version License: MIT

A high-performance SQLite logging handler for Python that stores log messages in an SQLite database. Built on top of Python's BufferingHandler, it provides efficient logging with minimal I/O overhead.

Features

  • High Performance: Uses buffering to minimize disk I/O operations
  • Thread-Safe: Designed to work in multi-threaded environments
  • Customizable Schema: Add custom fields to log tables
  • Background Flushing: Automatic periodic flushing of buffered logs
  • Optimized SQLite Settings: Uses WAL mode, memory-mapped I/O, and increased cache size
  • Rich Log Data: Captures comprehensive information for each log entry:
    • Basic log info (level, message, timestamp)
    • Source code context (filename, function, line number)
    • Thread and process information
    • Exception details with stack traces
    • Custom fields and extra data

Installation

pip install python_sqlite_log_handler

Basic Usage

import logging
from python_sqlite_log_handler import SQLiteLogHandler

# Set up logging
logger = logging.getLogger("app")
logger.setLevel(logging.DEBUG)

# Create and add the handler to the logger
handler = SQLiteLogHandler(db_path="logs.db")
logger.addHandler(handler)

# Log some messages
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("An error occurred", exc_info=True)

# Handler closes automatically. You may close it manually if needed
# handler.close()

Advanced Usage

Custom Fields and Extra Data

You can define additional fields for your log entries and pass extra data when logging:

from python_sqlite_log_handler import SQLiteLogHandler
import logging

# Create a handler with custom fields
custom_fields = [
    ("user_id", "TEXT"),
    ("request_id", "TEXT"),
    ("ip_address", "TEXT")
]

handler = SQLiteLogHandler(
    db_path="logs.db",
    table_name="application_logs",
    capacity=500,  # Flush every 500 logs
    flush_interval=10.0,  # Or every 10 seconds
    additional_fields=custom_fields
)

# Set up logger
logger = logging.getLogger("app")
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)

# Log with extra fields
extra = {
    "user_id": "user123",
    "request_id": "req-456-abc",
    "ip_address": "192.168.1.1",
    "custom_data": {"key": "value"}  # Will be stored in the extra JSON field
}

logger.info("User action performed", extra=extra)

Working with Multiple Databases and Tables

You can create multiple handlers for different loggers or purposes:

# Application logs
app_handler = SQLiteLogHandler(
    db_path="app_logs.db",
    table_name="app_events"
)

# Security logs in a separate database
security_handler = SQLiteLogHandler(
    db_path="security_logs.db",
    table_name="security_events",
    flush_interval=1.0  # Flush more frequently for security logs
)

# Set up loggers
app_logger = logging.getLogger("app")
app_logger.addHandler(app_handler)

security_logger = logging.getLogger("security")
security_logger.addHandler(security_handler)

Querying Logs

Since logs are stored in SQLite, you can use SQL to query them:

import sqlite3

# Connect to your log database
conn = sqlite3.connect("logs.db")
cursor = conn.cursor()

# Query logs by level and time
cursor.execute("""
    SELECT created_at, level_name, logger_name, message, extra
    FROM logs
    WHERE level >= ? AND created_at > ?
    ORDER BY created_at DESC
    LIMIT 100
""", (logging.WARNING, "2023-01-01T00:00:00"))

for row in cursor.fetchall():
    timestamp, level, logger, message, extra = row
    print(f"{timestamp} | {level:7s} | {logger:15s} | {message}")

conn.close()

Configuration Options

Parameter Description Default
db_path Path to the SQLite database file (required)
table_name Name of the table to store logs "logs"
capacity Number of records to buffer before writing 1000
flush_interval Time in seconds between periodic flushes 5.0
additional_fields List of (name, type) tuples for custom columns None

SQLite Performance Optimizations

The handler automatically configures SQLite for optimal logging performance:

  • WAL Mode: Enabled for better concurrency
  • Synchronous Mode: Set to NORMAL for improved write performance
  • Cache Size: Increased to 10MB
  • Memory-Mapped I/O: Enabled with 256MB allocation
  • Indexes: Created on commonly queried fields

Thread Safety

The handler is designed to be thread-safe and can be used in multi-threaded applications. Each thread maintains its own database connection, and access to the buffer is protected by locks.

License

This project is licensed under the MIT License - see the LICENSE.txt file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

python_sqlite_log_handler-1.1.0.tar.gz (10.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

python_sqlite_log_handler-1.1.0-py3-none-any.whl (7.4 kB view details)

Uploaded Python 3

File details

Details for the file python_sqlite_log_handler-1.1.0.tar.gz.

File metadata

File hashes

Hashes for python_sqlite_log_handler-1.1.0.tar.gz
Algorithm Hash digest
SHA256 318e512692a96aa5195e1d6f6a7c7360406aaf0e20708f3f03b451b287385b87
MD5 f6f6d8b5910cd1cdbff097c3e74060c1
BLAKE2b-256 6205d56cc0d49ce00cd0e0a1faa7489f761700ccd0d71848e908dfa6463d327e

See more details on using hashes here.

File details

Details for the file python_sqlite_log_handler-1.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for python_sqlite_log_handler-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c17492a20778c4f5d7683a8207932d76d499824e41ac80c4d368da839c72bb95
MD5 032185e8306225ec955882e4ef378971
BLAKE2b-256 a8b7c4f1874dd53e630690adc40ccbb7f6832a01336824397c999394f27b4514

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page