如何在django-auditlog中手动记录审计日志?
在django-auditlog中手动记录审计日志的解决方案
是否需要注册模型?
不需要强制注册目标模型。注册模型是让auditlog自动监听模型的增删改操作并生成日志,而手动记录审计日志时,你可以直接操作LogEntry模型,无论目标模型是否在auditlog中注册。
正确使用LogEntry.objects.log_create()的方法
log_create()是手动创建审计日志的核心方法,以下是完整示例,包含添加备注等额外信息的写法:
1. 基础示例(关联模型实例)
import json from auditlog.models import LogEntry from django.contrib.auth.models import User from your_app.models import YourModel # 替换为你的目标模型 # 获取要关联的模型实例 target_instance = YourModel.objects.get(pk=1) # 获取操作用户(无用户时可传None) current_user = User.objects.get(username="admin") # 手动创建带备注的审计日志 LogEntry.objects.log_create( instance=target_instance, action=LogEntry.Action.UPDATE, # 可选:CREATE/UPDATE/DELETE/OTHER changes=json.dumps({"status": ["draft", "published"]}), # 变更内容,JSON字符串 user=current_user, remarks="手动更新状态:将草稿改为已发布,原因是内容审核通过" )
2. 无关联实例的日志(系统操作类)
如果不需要关联特定模型实例,比如记录系统级操作:
import json from auditlog.models import LogEntry LogEntry.objects.log_create( instance=None, action=LogEntry.Action.OTHER, changes=json.dumps({"operation": ["cleanup", "completed"]}), user=None, # 无操作用户时设为None remarks="系统维护:清理过期临时文件完成" )
常见问题排查
changes格式错误:必须传入合法的JSON字符串,建议用json.dumps()生成字典的JSON格式,避免手动编写出错。- 备注不显示在admin后台:默认的
LogEntryAdmin可能不显示remarks字段,需要自定义admin类:from auditlog.admin import LogEntryAdmin as BaseLogEntryAdmin from auditlog.models import LogEntry from django.contrib import admin class CustomLogEntryAdmin(BaseLogEntryAdmin): list_display = (*BaseLogEntryAdmin.list_display, 'remarks') admin.site.unregister(LogEntry) admin.site.register(LogEntry, CustomLogEntryAdmin) - 权限报错:确保执行代码的用户有
add_logentry权限,后台任务中可使用超级用户账号执行。
内容的提问来源于stack exchange,提问作者Janitorfish
相关产品推荐
相关产品推荐

