Skip to main content

Django Operation Logger (django_ops_logger)

一款功能强大、即插即用的 Django 全方位操作日志记录应用。它能够在不侵入业务逻辑的情况下,记录请求、数据库查询、缓存操作、信号等的全生命周期日志。

功能特性

  • 零侵入:只需在 INSTALLED_APPS 和 MIDDLEWARE 中注册即可使用。
  • 全链路追踪:通过唯一的 Trace ID 将 HTTP 请求、数据库查询、缓存操作和信号串联起来。
  • 高性能:使用异步队列和后台 Worker 进行批量数据库写入,确保不影响主业务性能。
  • 数据脱敏:自动对敏感数据(如密码、Token)进行脱敏处理。
  • 全面覆盖:
    • HTTP 请求(方法、路径、用户、IP、耗时)
    • 数据库查询(SQL 语句、参数、耗时)
    • 缓存操作(Get/Set/Delete、命中/未命中)
    • 用户认证(登录成功/失败)
    • 系统启动事件

安装步骤

  1. 将 django_ops_logger 包复制到您的 Django 项目根目录。

  2. 添加到 INSTALLED_APPS:

INSTALLED_APPS = [
    # ...
    'django_ops_logger',
]
  1. 添加到 MIDDLEWARE:

注意:建议将其放置在 AuthenticationMiddleware 之后,以便能够捕获用户信息。

MIDDLEWARE = [
    # ...
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django_ops_logger.middleware.RequestLogMiddleware', 
    # ...
]
  1. 运行数据库迁移:
python manage.py makemigrations django_ops_logger
python manage.py migrate

配置说明

在 settings.py 中添加 DJANGO_OPS_LOGGER 配置项以自定义行为:

DJANGO_OPS_LOGGER = {
    'ENABLED': True,             # 总开关
    'SQL_LOG_ENABLE': True,      # 记录数据库查询
    'JWT_SECRET_KEY': 'jwt key', # 必须和setting一致
    'CACHE_LOG_ENABLE': False,   # 记录缓存操作(默认关闭,因为日志量可能很大)
}

使用方法

安装完成后,日志记录器会自动工作。您可以通过 Django Admin(如果已注册)或直接通过 OperationLog 模型查询日志。

查询日志

from django_ops_logger.models import OperationLog

# 获取特定 Trace ID 的所有日志
logs = OperationLog.objects.filter(trace_id='your-trace-id')

# 获取慢查询(耗时超过 500ms)
slow_queries = OperationLog.objects.filter(
    operation_type='db', 
    duration__gt=500
)

手动记录日志

您也可以在视图或业务逻辑中手动记录自定义事件:

from django_ops_logger.queue import enqueue_log
from django_ops_logger.models import OperationLog
from django_ops_logger.context import TrackerContext
from django.utils import timezone

def my_custom_logic():
    # ... 业务逻辑 ...
    
    enqueue_log(
        trace_id=TrackerContext.get_trace_id(),
        operation_type=OperationLog.OpType.CUSTOM,
        level='INFO',
        start_time=timezone.now(),
        details={'action': 'payment_processed', 'amount': 100}
    )

架构设计

  • 上下文追踪:使用 contextvars 在请求生命周期内维护 trace_id。
  • 中间件:捕获请求/响应周期,并处理异常日志。
  • 包装器 (Wrappers):Monkey-patch 数据库和缓存后端以拦截底层操作。
  • 异步队列:所有日志被推送到内存队列中,并由后台线程批量刷新到数据库,以确保对响应时间的影响降至最低。

Metadata

Release files for django-ops-logger 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-ops-logger 0.1.1
File Size Uploaded Provenance Actions
django_ops_logger-0.1.1.tar.gz 12.6 kB Without provenance Details for django_ops_logger-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-ops-logger 0.1.1
File Interpreter ABI Platform Actions
django_ops_logger-0.1.1-py3-none-any.whl Python 3 none any Details for django_ops_logger-0.1.1-py3-none-any.whl

Total release size: 26.8 kB

Release files / django_ops_logger-0.1.1.tar.gz

Download URL django_ops_logger-0.1.1.tar.gz
Size 12.6 kB
Tags Source
SHA-256 checksum
How to use checksums
2adee68fe20911c6504468d8bd8a5ffaecd9301dc5cbe2022b22bf9fad36a870
BLAKE2b-256 checksum
How to use checksums
066ad8afaf87607fc1ee179e52f66a359a6be2261a3d6cc775b02fb242c0aa8a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.12.9

Release files / django_ops_logger-0.1.1-py3-none-any.whl

Download URL django_ops_logger-0.1.1-py3-none-any.whl
Size 14.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c666e96614f7c6bb52d2adfafefdc33670484333ad9a3cd57053a509ae732d53
BLAKE2b-256 checksum
How to use checksums
728ab51edb7815211ce24dfddca82a6b0fb2db264b54fc42c24fcd283e3ccc5c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.12.9

Security for django-ops-logger 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page