Skip to main content

A module to add logging in json format that an AI could easily understand.

Project description

AI Logger

A Python module for structured logging in a format that's easily parsable by AI systems. It provides comprehensive, context-rich logs to help AI systems understand application behavior.

Features

  • JSON-formatted logs optimized for AI consumption
  • Automatic capturing of context (filename, line number, function)
  • Decorators for easy function and class wrapping
  • Support for different event types (model, data, error)
  • Simple integration with existing Python logging

Installation

# Install from PyPI
pip install ai-logger

# Or install from source using Poetry
poetry install

Example Usage

The package includes a complete example with Click CLI commands to demonstrate the AI Logger functionality:

# Run all examples
poetry run run-example run-all

# Run just the function example
poetry run run-example run-function --size 200

# Run just the class example
poetry run run-example run-class --initial 10 --operations 8

# Run just the module example
poetry run run-example run-module

Configuration

AI Logger can be configured through several methods:

Using a Configuration File

Create a JSON configuration file like:

{
  "verbose": true,
  "database": {
    "use_db": true,
    "dbname": "my_logger_db",
    "user": "postgres",
    "password": "secretpassword",
    "host": "localhost",
    "port": "5432",
    "table_name": "ai_logs"
  },
  "logging": {
    "level": "INFO",
    "log_to_file": true,
    "log_dir": "logs",
    "log_to_console": true
  }
}

You can specify your custom configuration file in several ways:

  1. Environment variable:

    export AI_LOGGER_CONFIG=/path/to/your/config.json
    
  2. Programmatic loading:

    from ai_logger import reload_config
    reload_config("/path/to/your/config.json")
    
  3. When initializing:

    from ai_logger import init_ai_logger
    init_ai_logger(app_name="my_app", config_path="/path/to/your/config.json")
    

Basic Code Usage

Direct Import and Usage

# Import directly from the package
import logging
from ai_logger import init_ai_logger, auto_wrap, auto_wrap_class

# Initialize the global logger
logger = init_ai_logger(
    app_name="my_app",
    log_file="ai_logs.json",
    console_output=True,
    log_level=logging.INFO,  # Optional, defaults to WARNING
    capture_loggers=["sqlalchemy", "uvicorn", "custom_logger_name"],  # Optional, capture other loggers
    capture_all_loggers=False,  # Optional, capture all Python loggers
    use_db=True,  # Optional, enable database logging
    db_name="my_logger_db",  # Optional, custom database name
    db_table="my_app_logs"  # Optional, custom table name (defaults to app_name)
)

# Log a model event
logger.log_model_event(
    model_name="gpt-4",
    event_type="inference",
    input_tokens=150,
    output_tokens=30,
    latency_ms=500
)

# Use the auto_wrap decorator for functions
@auto_wrap(component="data_processor")
def process_data(data):
    # Function code here
    return result

# Use the auto_wrap_class decorator for classes
@auto_wrap_class(component="ml_model")
class MyModel:
    def predict(self, inputs):
        # All methods are automatically wrapped
        return prediction
    
    def train(self, dataset):
        # Training is also logged
        return training_results

Advanced Usage with Manual Logger

from ai_logger import AILogger

# Create a logger instance manually
custom_logger = AILogger(
    app_name="custom_app",
    log_file="custom_logs.json",
    console_output=True,
    use_db=True,
    db_name="custom_logger_db",
    db_table="custom_logs"
)

# Log a data event
custom_logger.log_data_event(
    data_source="database",
    event_type="query",
    record_count=1250,
    details={"query_time_ms": 45, "table": "users"}
)

# Log an error event
try:
    # Some code that might fail
    result = 1 / 0
except Exception as e:
    custom_logger.log_error(
        error_type="ZeroDivisionError",
        error_message=str(e),
        component="math_operations",
        include_traceback=True,
        severity="ERROR"
    )

# Wrap a function with this specific logger
@custom_logger.wrap_function(component="data_processor")
def process_data(data):
    # Function code here
    return result

# Wrap an entire class with this specific logger
@custom_logger.wrap_class(component="ml_model")
class MyModel:
    def predict(self, inputs):
        # Method code here
        return prediction

Log Structure

Events are stored as JSON objects with the following structure:

{
  "event_id": "unique-uuid",
  "timestamp": "2023-07-20T14:30:00.123456",
  "event_type": "inference",
  "component": "model",
  "file_name": "/path/to/file.py",
  "line_number": 42,
  "function_name": "predict",
  "model_name": "gpt-4",
  "input_tokens": 150,
  "output_tokens": 30,
  "latency_ms": 500,
  "details": {
    "app_name": "my_app",
    "custom_field": "custom_value"
  }
}

License

MIT

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

ai_logger-0.1.2.tar.gz (17.4 kB view details)

Uploaded Source

Built Distribution

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

ai_logger-0.1.2-py3-none-any.whl (20.6 kB view details)

Uploaded Python 3

File details

Details for the file ai_logger-0.1.2.tar.gz.

File metadata

  • Download URL: ai_logger-0.1.2.tar.gz
  • Upload date:
  • Size: 17.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.9.22

File hashes

Hashes for ai_logger-0.1.2.tar.gz
Algorithm Hash digest
SHA256 9ff42b13646f7dcd435cf6c3a9980cd5872821729fcce5780a27b9dd8229ac84
MD5 81c033016d2f7c9a66469677a64f2e7f
BLAKE2b-256 dec997911024e94ced30cf38043a3080759f92488700db8957af094bfad8b3dc

See more details on using hashes here.

File details

Details for the file ai_logger-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: ai_logger-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 20.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.9.22

File hashes

Hashes for ai_logger-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 deb9be12706549dfc9a4c7474dae9513bd7b15b0e8dad776500e9aee15646ca1
MD5 0b68782cae8e02887857d33e09352241
BLAKE2b-256 c69b65c62f09390aa3631c1ee41b4327ee558bb45fdacfbf2b153e3de6ec3fb3

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