quirtylog.sqlite_logger

sqlite_logger.py

This module provides the SQLiteHandler class, a thread-safe logging handler for storing log records in an SQLite database.

Classes

SQLiteHandler([db])

Thread-safe logging handler for SQLite.

class quirtylog.sqlite_logger.SQLiteHandler(db='log.db')

Bases: Handler

Thread-safe logging handler for SQLite.

This class extends the logging.Handler class to provide a thread-safe logging handler for storing log records in an SQLite database.

Initialize the SQLiteHandler instance.

Parameters:

db (Path | str) – A path for creating the SQLite database (default: ‘log.db’).

Raises:

TypeError – If db is not a string or a Path object.

This method initializes the SQLiteHandler instance by connecting to the SQLite database specified by the db parameter. It also executes the initial SQL statement to create the log table if it does not exist.

Example:

# Initialize SQLiteHandler with the default database path
sqlite_handler = SQLiteHandler()

# Initialize SQLiteHandler with a custom database path
sqlite_handler_custom = SQLiteHandler(db='/path/to/logs/my_logs.db')
property log_table: str

Return the name of the table in the SQLite database

static format_time(record)

Create a time-stamp for the log record.

Parameters:

record (LogRecord) – The log record to which the time-stamp will be added.

This static method adds a time-stamp to the provided log record. The time-stamp is generated based on the created attribute of the log record, representing the time of log record creation.

Example:

# Example usage of format_time in the SQLiteHandler class
log_record = logging.LogRecord('name', logging.ERROR, 'pathname', 1, 'Log message', (), None)
SQLiteHandler.format_time(log_record)
print(log_record.dbtime)  # Output: '2023-12-18 15:30:45' (example timestamp)
emit(record)

Emit the log message by formatting and inserting the log record into the SQLite database.

Parameters:

record (LogRecord) – The log record to be emitted.

This method formats the log record using the format and format_time methods, and then inserts the formatted log record into the SQLite database. If the log record contains exception information, it is formatted and stored in the exc_text attribute of the record.

Note

  • This method assumes that the log record follows the structure expected by the SQL insertion statement.

  • The method opens a new connection to the SQLite database for each log record insertion, which may not be efficient in high-throughput scenarios.

Example:

# Example usage of emit in the SQLiteHandler class
log_record = logging.LogRecord('name', logging.ERROR, 'pathname', 1, 'Log message', (), None)
sqlite_handler = SQLiteHandler(db='/path/to/logs/my_logs.db')
sqlite_handler.emit(log_record)