A simple Python library for logging events to PostgreSQL database
Project description
Event Journal
A simple Python library for logging events to PostgreSQL database with a clean API. Perfect for audit trails, user activity tracking, and system event logging. No Django or web framework required!
🚀 Features
- Zero Configuration - Pre-configured database connection
- Simple API - Just import and log events
- No Framework Required - Works with any Python application
- No Migrations - Assumes table already exists
- Utility Functions - Extract IP addresses and user agents
- Production Ready - Optimized for performance and reliability
- Context Manager Support - Automatic connection management
Installation
pip install event-journal
Or install from source:
git clone https://github.com/amolsr/event_journal.git
cd event_journal
pip install -e .
Database Configuration
The library comes with pre-configured database settings for immediate use. No additional configuration is required - the library will automatically connect to the database.
Setup
Quick Start
No setup required! Just install and use:
pip install event-journal
from event_journal import log_event
log_event('your_event_type', event_info={...})
Database Setup
- Create the event journal table in your PostgreSQL database:
-- Run this SQL script in your database
\i create_event_journal_table.sql
- Test the connection:
python quick_start.py
Usage
Basic Usage
The library comes with pre-configured database settings, so you can use it in any Python script without any setup:
from event_journal import log_event
# Just log events - assumes EventJournal table already exists!
log_event(
event_type='user_login',
user_id=123,
event_info={
'login_method': 'email',
'success': True
},
ip_address='192.168.1.1',
user_agent='Mozilla/5.0...'
)
Prerequisites: The EventJournal table must already exist in your database.
Advanced Usage with Database Handler
For more control over database connections:
from event_journal import DatabaseHandler, EventJournal
# Create a custom database handler
db_handler = DatabaseHandler(
host='your-host',
port=5432,
database='your-database',
user='your-user',
password='your-password'
)
# Use context manager for automatic connection management
with db_handler:
# Log an event
event = EventJournal.log_event(
event_type='user_login',
user_id=123,
event_info={'login_method': 'email'},
db_handler=db_handler
)
Convenience Functions
The library provides convenience functions for common event types:
from event_journal import log_user_login, log_file_upload, log_api_request
# Log user login
log_user_login(
user_id=123,
login_method='email',
ip_address='192.168.1.1',
user_agent='Mozilla/5.0...'
)
# Log file upload
log_file_upload(
user_id=123,
file_id='file_456',
filename='document.pdf',
file_type='application/pdf',
file_size=2048000,
ip_address='192.168.1.1'
)
# Log API request
log_api_request(
endpoint='/api/upload',
method='POST',
status_code=200,
user_id=123,
response_time_ms=150
)
Utility Functions
The library provides utility functions for extracting client information:
from event_journal.utils import get_client_ip, get_user_agent
# With Flask request headers
ip_address = get_client_ip(dict(request.headers))
user_agent = get_user_agent(dict(request.headers))
# With custom headers dictionary
headers = {'X-Forwarded-For': '192.168.1.1', 'User-Agent': 'Mozilla/5.0...'}
ip_address = get_client_ip(headers)
user_agent = get_user_agent(headers)
API Reference
log_event()
Log an event to the database.
Parameters:
event_type(str): Type of event being loggeduser_id(int, optional): ID of the user associated with this eventevent_info(dict, optional): Additional event informationip_address(str, optional): Client IP addressuser_agent(str, optional): Client user agent stringtimestamp(datetime, optional): Event timestamp (defaults to now)
Returns:
EventJournal: The created EventJournal instance
DatabaseHandler
Manage database connections and operations.
Parameters:
host(str): Database hostport(int): Database portdatabase(str): Database nameuser(str): Database usernamepassword(str): Database passwordsslmode(str): SSL mode for connection
Methods:
test_connection(): Test database connectioncheck_table_exists(): Check if event journal table existscreate_event(): Create a new eventget_event(event_id): Get event by IDget_events(): Get events with filteringcount_events(): Count events with filteringdelete_event(event_id): Delete event by ID
EventJournal
Model for event journal entries.
Attributes:
id: Database IDevent_type: Type of eventuser_id: User ID (optional)event_info: Event information dictionaryip_address: Client IP addressuser_agent: Client user agenttimestamp: Event timestampcreated_at: Creation timestamp
Methods:
to_dict(): Convert to dictionaryfrom_dict(data): Create from dictionarylog_event(): Class method to log events
Database Schema
The library uses a PostgreSQL table with the following structure:
CREATE TABLE event_journal (
id SERIAL PRIMARY KEY,
event_type VARCHAR(100) NOT NULL,
user_id INTEGER NULL,
event_info JSONB DEFAULT '{}',
ip_address INET NULL,
user_agent TEXT DEFAULT '',
timestamp TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
Fields:
id: Primary key (auto-incrementing)event_type: Type of event (VARCHAR, max 100 chars)user_id: User ID (INTEGER, nullable)event_info: JSON field containing event data (JSONB)ip_address: Client IP address (INET type)user_agent: Client user agent (TEXT)timestamp: Event timestamp (TIMESTAMP WITH TIME ZONE)created_at: Record creation timestamp (TIMESTAMP WITH TIME ZONE)
Indexes:
- Primary key on
id - Index on
event_type - Index on
user_id - Index on
timestamp - Composite index on
event_type, timestamp
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
📝 License
This project is licensed under the MIT License - see the LICENSE file for details.
🔗 Links
- Repository: https://github.com/amolsr/event_journal
- PyPI Package: https://pypi.org/project/event-journal/
- Issues: https://github.com/amolsr/event_journal/issues
📊 Stats
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file event_journal-1.1.0.tar.gz.
File metadata
- Download URL: event_journal-1.1.0.tar.gz
- Upload date:
- Size: 15.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
88ac4276afbd1bb12a28d379da3fc82e9f2b1b899ce76f405630b0494f8f6fce
|
|
| MD5 |
9a76a2da2d2b069f8f0d3ad383af36ec
|
|
| BLAKE2b-256 |
303d8cc773872159f49991e8517c0971157d986be5400780cff962d8d90c9cdb
|
Provenance
The following attestation bundles were made for event_journal-1.1.0.tar.gz:
Publisher:
publish.yml on amolsr/event_journal
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
event_journal-1.1.0.tar.gz -
Subject digest:
88ac4276afbd1bb12a28d379da3fc82e9f2b1b899ce76f405630b0494f8f6fce - Sigstore transparency entry: 575596853
- Sigstore integration time:
-
Permalink:
amolsr/event_journal@aac01e285317db251e4481f7728360efd04f08d0 -
Branch / Tag:
refs/tags/v1.0.0 - Owner: https://github.com/amolsr
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@aac01e285317db251e4481f7728360efd04f08d0 -
Trigger Event:
release
-
Statement type:
File details
Details for the file event_journal-1.1.0-py3-none-any.whl.
File metadata
- Download URL: event_journal-1.1.0-py3-none-any.whl
- Upload date:
- Size: 14.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5d036963464c9f6d044a902a2eebe068cb049e0f03cfe0079cd153ebfc6cd1a6
|
|
| MD5 |
dec9acb0e7057828ef1b14719ca85133
|
|
| BLAKE2b-256 |
8cd6d149f5dd911bf352cfd986f832f020265a765b56ecb4da7e211bec63e854
|
Provenance
The following attestation bundles were made for event_journal-1.1.0-py3-none-any.whl:
Publisher:
publish.yml on amolsr/event_journal
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
event_journal-1.1.0-py3-none-any.whl -
Subject digest:
5d036963464c9f6d044a902a2eebe068cb049e0f03cfe0079cd153ebfc6cd1a6 - Sigstore transparency entry: 575596858
- Sigstore integration time:
-
Permalink:
amolsr/event_journal@aac01e285317db251e4481f7728360efd04f08d0 -
Branch / Tag:
refs/tags/v1.0.0 - Owner: https://github.com/amolsr
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@aac01e285317db251e4481f7728360efd04f08d0 -
Trigger Event:
release
-
Statement type: