django-audit-library


Namedjango-audit-library JSON
Version 1.0.3 PyPI version JSON
download
home_pagehttps://github.com/mcwamsie/django_audit-library
SummaryA comprehensive Django audit logging library for tracking model changes, user actions, and system events
upload_time2025-08-03 19:05:11
maintainerNone
docs_urlNone
authorTinashe Makwarimba
requires_python>=3.8
licenseMIT
keywords django audit logging security tracking changes
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Django Audit Library

A comprehensive Django audit logging library that provides automatic tracking of model changes, user actions, login attempts, data exports, and system events.

## Features

- **Automatic Model Tracking**: Automatically logs CREATE, UPDATE, and DELETE operations on all Django models
- **User Authentication Tracking**: Logs login/logout attempts and failures
- **Data Export Auditing**: Tracks data exports with metadata
- **System Event Logging**: Captures system errors, warnings, and performance issues
- **Security Monitoring**: Detects suspicious requests and activities
- **Admin Interface**: Beautiful Django admin interface for viewing audit logs
- **Thread-Safe**: Uses thread-local storage for request context
- **Migration-Safe**: Automatically detects and skips logging during migrations

## Installation

1. Install the package:
```bash
pip install django-audit-library
```

2. Add `audit` to your `INSTALLED_APPS` in Django settings:
```python
INSTALLED_APPS = [
    # ... your other apps
    'audit',
]
```

3. Add the audit middleware to your `MIDDLEWARE` setting:
```python
MIDDLEWARE = [
    # ... your other middleware
    'audit.middleware.AuditMiddleware',
    'audit.middleware.SecurityAuditMiddleware',  # Optional: for security monitoring
]
```

4. Run migrations:
```bash
python manage.py makemigrations audit
python manage.py migrate audit
```

## Usage

### Automatic Logging

Once installed and configured, the library will automatically start logging:

- Model changes (create, update, delete)
- User login/logout events
- Failed login attempts
- System errors and exceptions

### Manual Logging

You can also manually log events using the utility functions:

```python
from audit.utils import log_audit_event, log_system_event, log_data_export

# Log a custom audit event
log_audit_event(
    user=request.user,
    action='CUSTOM_ACTION',
    content_object=some_model_instance,
    changes={'field': 'new_value'},
    reason='Custom reason',
    request=request
)

# Log a system event
log_system_event(
    event_type='INFO',
    title='Custom Event',
    description='Something important happened',
    user=request.user,
    request=request
)

# Log a data export
log_data_export(
    user=request.user,
    export_type='User Data',
    file_format='CSV',
    record_count=100,
    file_size=1024,
    filters={'active': True},
    request=request
)
```

### Using the Audit Mixin

For class-based views, you can use the `AuditMixin`:

```python
from audit.utils import AuditMixin
from django.views.generic import DetailView

class MyDetailView(AuditMixin, DetailView):
    model = MyModel
    
    def get_object(self):
        obj = super().get_object()
        self.log_view_access(self.request, obj)
        return obj
```

### Getting Audit Summaries

```python
from audit.utils import get_audit_summary

# Get system-wide summary for last 30 days
summary = get_audit_summary(days=30)

# Get summary for specific user
summary = get_audit_summary(user=request.user, days=7)
```

## Models

The library provides several models for different types of audit data:

### AuditLog
Tracks all model changes and user actions with:
- User who performed the action
- Action type (CREATE, UPDATE, DELETE, VIEW, LOGIN, LOGOUT, etc.)
- Object being modified (using generic foreign keys)
- Before/after values for changes
- IP address, user agent, session information
- Timestamp and additional metadata

### LoginAttempt
Tracks authentication attempts with:
- Username and status (SUCCESS, FAILED, BLOCKED)
- IP address and user agent
- Geographic information (optional)
- Failure reasons

### DataExport
Tracks data exports with:
- User and export type
- File format and size
- Record count and filters applied
- Download tracking

### SystemEvent
Tracks system-level events with:
- Event type (ERROR, WARNING, INFO, SECURITY, PERFORMANCE)
- Technical details (module, function, line number)
- Error codes and stack traces
- Resolution tracking

## Admin Interface

The library provides a comprehensive Django admin interface with:

- Read-only views for all audit data
- Advanced filtering and searching
- Formatted display of changes and technical details
- Date hierarchies for easy navigation
- Proper permissions (only superusers can delete)

## Configuration

### Settings

You can customize the behavior with these optional settings:

```python
# In your Django settings.py

# Skip auditing for specific models
AUDIT_SKIP_MODELS = [
    'auth.Session',
    'contenttypes.ContentType',
]

# Skip auditing for specific actions
AUDIT_SKIP_ACTIONS = ['VIEW']

# Custom user model (if you're using one)
AUTH_USER_MODEL = 'your_app.CustomUser'
```

### Middleware Options

The library includes two middleware classes:

1. **AuditMiddleware**: Core functionality for request tracking
2. **SecurityAuditMiddleware**: Additional security monitoring (optional)

## Performance Considerations

- The library uses efficient database queries and indexing
- Thread-local storage minimizes performance impact
- Automatic migration detection prevents issues during deployments
- Configurable to skip certain models or actions if needed

## Security Features

- Tracks suspicious request patterns
- Monitors unusual user agents
- Logs slow requests for performance monitoring
- Captures and logs system exceptions
- Geographic tracking for login attempts (optional)

## Requirements

- Django 3.2+
- Python 3.8+

## License

MIT License - see LICENSE file for details.

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

## Support

For issues and questions, please use the GitHub issue tracker.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/mcwamsie/django_audit-library",
    "name": "django-audit-library",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "django, audit, logging, security, tracking, changes",
    "author": "Tinashe Makwarimba",
    "author_email": "Tinashe Makwarimba <tinashe@mcwamsie.com>",
    "download_url": "https://files.pythonhosted.org/packages/f8/a4/b5bd456e4dc20a7f44050762aed01892f0737a58d12806d5432664f13720/django_audit_library-1.0.3.tar.gz",
    "platform": null,
    "description": "# Django Audit Library\r\n\r\nA comprehensive Django audit logging library that provides automatic tracking of model changes, user actions, login attempts, data exports, and system events.\r\n\r\n## Features\r\n\r\n- **Automatic Model Tracking**: Automatically logs CREATE, UPDATE, and DELETE operations on all Django models\r\n- **User Authentication Tracking**: Logs login/logout attempts and failures\r\n- **Data Export Auditing**: Tracks data exports with metadata\r\n- **System Event Logging**: Captures system errors, warnings, and performance issues\r\n- **Security Monitoring**: Detects suspicious requests and activities\r\n- **Admin Interface**: Beautiful Django admin interface for viewing audit logs\r\n- **Thread-Safe**: Uses thread-local storage for request context\r\n- **Migration-Safe**: Automatically detects and skips logging during migrations\r\n\r\n## Installation\r\n\r\n1. Install the package:\r\n```bash\r\npip install django-audit-library\r\n```\r\n\r\n2. Add `audit` to your `INSTALLED_APPS` in Django settings:\r\n```python\r\nINSTALLED_APPS = [\r\n    # ... your other apps\r\n    'audit',\r\n]\r\n```\r\n\r\n3. Add the audit middleware to your `MIDDLEWARE` setting:\r\n```python\r\nMIDDLEWARE = [\r\n    # ... your other middleware\r\n    'audit.middleware.AuditMiddleware',\r\n    'audit.middleware.SecurityAuditMiddleware',  # Optional: for security monitoring\r\n]\r\n```\r\n\r\n4. Run migrations:\r\n```bash\r\npython manage.py makemigrations audit\r\npython manage.py migrate audit\r\n```\r\n\r\n## Usage\r\n\r\n### Automatic Logging\r\n\r\nOnce installed and configured, the library will automatically start logging:\r\n\r\n- Model changes (create, update, delete)\r\n- User login/logout events\r\n- Failed login attempts\r\n- System errors and exceptions\r\n\r\n### Manual Logging\r\n\r\nYou can also manually log events using the utility functions:\r\n\r\n```python\r\nfrom audit.utils import log_audit_event, log_system_event, log_data_export\r\n\r\n# Log a custom audit event\r\nlog_audit_event(\r\n    user=request.user,\r\n    action='CUSTOM_ACTION',\r\n    content_object=some_model_instance,\r\n    changes={'field': 'new_value'},\r\n    reason='Custom reason',\r\n    request=request\r\n)\r\n\r\n# Log a system event\r\nlog_system_event(\r\n    event_type='INFO',\r\n    title='Custom Event',\r\n    description='Something important happened',\r\n    user=request.user,\r\n    request=request\r\n)\r\n\r\n# Log a data export\r\nlog_data_export(\r\n    user=request.user,\r\n    export_type='User Data',\r\n    file_format='CSV',\r\n    record_count=100,\r\n    file_size=1024,\r\n    filters={'active': True},\r\n    request=request\r\n)\r\n```\r\n\r\n### Using the Audit Mixin\r\n\r\nFor class-based views, you can use the `AuditMixin`:\r\n\r\n```python\r\nfrom audit.utils import AuditMixin\r\nfrom django.views.generic import DetailView\r\n\r\nclass MyDetailView(AuditMixin, DetailView):\r\n    model = MyModel\r\n    \r\n    def get_object(self):\r\n        obj = super().get_object()\r\n        self.log_view_access(self.request, obj)\r\n        return obj\r\n```\r\n\r\n### Getting Audit Summaries\r\n\r\n```python\r\nfrom audit.utils import get_audit_summary\r\n\r\n# Get system-wide summary for last 30 days\r\nsummary = get_audit_summary(days=30)\r\n\r\n# Get summary for specific user\r\nsummary = get_audit_summary(user=request.user, days=7)\r\n```\r\n\r\n## Models\r\n\r\nThe library provides several models for different types of audit data:\r\n\r\n### AuditLog\r\nTracks all model changes and user actions with:\r\n- User who performed the action\r\n- Action type (CREATE, UPDATE, DELETE, VIEW, LOGIN, LOGOUT, etc.)\r\n- Object being modified (using generic foreign keys)\r\n- Before/after values for changes\r\n- IP address, user agent, session information\r\n- Timestamp and additional metadata\r\n\r\n### LoginAttempt\r\nTracks authentication attempts with:\r\n- Username and status (SUCCESS, FAILED, BLOCKED)\r\n- IP address and user agent\r\n- Geographic information (optional)\r\n- Failure reasons\r\n\r\n### DataExport\r\nTracks data exports with:\r\n- User and export type\r\n- File format and size\r\n- Record count and filters applied\r\n- Download tracking\r\n\r\n### SystemEvent\r\nTracks system-level events with:\r\n- Event type (ERROR, WARNING, INFO, SECURITY, PERFORMANCE)\r\n- Technical details (module, function, line number)\r\n- Error codes and stack traces\r\n- Resolution tracking\r\n\r\n## Admin Interface\r\n\r\nThe library provides a comprehensive Django admin interface with:\r\n\r\n- Read-only views for all audit data\r\n- Advanced filtering and searching\r\n- Formatted display of changes and technical details\r\n- Date hierarchies for easy navigation\r\n- Proper permissions (only superusers can delete)\r\n\r\n## Configuration\r\n\r\n### Settings\r\n\r\nYou can customize the behavior with these optional settings:\r\n\r\n```python\r\n# In your Django settings.py\r\n\r\n# Skip auditing for specific models\r\nAUDIT_SKIP_MODELS = [\r\n    'auth.Session',\r\n    'contenttypes.ContentType',\r\n]\r\n\r\n# Skip auditing for specific actions\r\nAUDIT_SKIP_ACTIONS = ['VIEW']\r\n\r\n# Custom user model (if you're using one)\r\nAUTH_USER_MODEL = 'your_app.CustomUser'\r\n```\r\n\r\n### Middleware Options\r\n\r\nThe library includes two middleware classes:\r\n\r\n1. **AuditMiddleware**: Core functionality for request tracking\r\n2. **SecurityAuditMiddleware**: Additional security monitoring (optional)\r\n\r\n## Performance Considerations\r\n\r\n- The library uses efficient database queries and indexing\r\n- Thread-local storage minimizes performance impact\r\n- Automatic migration detection prevents issues during deployments\r\n- Configurable to skip certain models or actions if needed\r\n\r\n## Security Features\r\n\r\n- Tracks suspicious request patterns\r\n- Monitors unusual user agents\r\n- Logs slow requests for performance monitoring\r\n- Captures and logs system exceptions\r\n- Geographic tracking for login attempts (optional)\r\n\r\n## Requirements\r\n\r\n- Django 3.2+\r\n- Python 3.8+\r\n\r\n## License\r\n\r\nMIT License - see LICENSE file for details.\r\n\r\n## Contributing\r\n\r\n1. Fork the repository\r\n2. Create a feature branch\r\n3. Make your changes\r\n4. Add tests\r\n5. Submit a pull request\r\n\r\n## Support\r\n\r\nFor issues and questions, please use the GitHub issue tracker.\r\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A comprehensive Django audit logging library for tracking model changes, user actions, and system events",
    "version": "1.0.3",
    "project_urls": {
        "Bug Tracker": "https://github.com/mcwamsie/django_audit_library/issues",
        "Documentation": "https://github.com/mcwamsie/django_audit_library#readme",
        "Homepage": "https://github.com/mcwamsie/django_audit_library",
        "Repository": "https://github.com/mcwamsie/django_audit_library.git"
    },
    "split_keywords": [
        "django",
        " audit",
        " logging",
        " security",
        " tracking",
        " changes"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "38872b48005e39660cef32d7f2eedcf55e33d945e2faf67ee47079510fb5b877",
                "md5": "e0e867f8eee16da24b387b6fef7b0743",
                "sha256": "48c9bc456bbac24bdc2cefc958497a2044d70a57de3d4f89c56c1f0931e64eb7"
            },
            "downloads": -1,
            "filename": "django_audit_library-1.0.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "e0e867f8eee16da24b387b6fef7b0743",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 17289,
            "upload_time": "2025-08-03T19:05:10",
            "upload_time_iso_8601": "2025-08-03T19:05:10.030097Z",
            "url": "https://files.pythonhosted.org/packages/38/87/2b48005e39660cef32d7f2eedcf55e33d945e2faf67ee47079510fb5b877/django_audit_library-1.0.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "f8a4b5bd456e4dc20a7f44050762aed01892f0737a58d12806d5432664f13720",
                "md5": "d2db84c767790ae1174a666569063899",
                "sha256": "78f5e3a0900661ce08dd07d06aa7bc2d44afa4611b2b8130d86a93905255da12"
            },
            "downloads": -1,
            "filename": "django_audit_library-1.0.3.tar.gz",
            "has_sig": false,
            "md5_digest": "d2db84c767790ae1174a666569063899",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 17721,
            "upload_time": "2025-08-03T19:05:11",
            "upload_time_iso_8601": "2025-08-03T19:05:11.426914Z",
            "url": "https://files.pythonhosted.org/packages/f8/a4/b5bd456e4dc20a7f44050762aed01892f0737a58d12806d5432664f13720/django_audit_library-1.0.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-03 19:05:11",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "mcwamsie",
    "github_project": "django_audit-library",
    "github_not_found": true,
    "lcname": "django-audit-library"
}
        
Elapsed time: 2.20402s