gpt4 book ai didi

python - django数据库查询日志行号

转载 作者:行者123 更新时间:2023-12-01 08:36:55 25 4
gpt4 key购买 nike

我正在 Django 中记录我的数据库查询以及路径名和行号。

现在我收到这些日志:

07/12/2018 14:25:00 调试 django.db.backends utils **/Users/XXXXX/.idea/lib/python2.7/site-packages/django/db/backends/utils .py:89**
(0.340) 从“元数据”中选择“元数据”.“元名称”、“元数据”.“描述”、“元数据”.“属性”,其中“元数据”.“元名称”=“日期类型”; args=('date_type',)

对于所有查询,我得到相同的路径和行号。有什么方法可以从我的主应用程序中捕获行号,而不是从 utils 中捕获行号。

当前日志记录实现:

LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'color'
},
},
'loggers': {
'django.db.backends': {
'handlers': ['console'],
'level': 'DEBUG',
'propogate': True,
}
}
}

使用 python 2.7 和 django 1.9

最佳答案

来自用户@will-keeling的稍微优化的版本

Django 的日志配置,用于每个数据库请求的输出行号。

注意:如果你想用它进行测试,你需要为测试设置 DEBUG=True How do you set DEBUG to True when running a Django test?

import logging
import traceback
from django.conf import settings


class StackInfoHandler(logging.StreamHandler):
trim = 5

def emit(self, record):
super(StackInfoHandler, self).emit(record)
trace = traceback.format_stack()
stack1 = [str(row) for row in trace]
stack2 = [s for s in stack1 if settings.BASE_DIR in s and 'format_stack' not in s]
stack3 = [s for s in stack2 if 'test' not in s]
if not stack3:
stack3 = stack2 # include test call
if stack3:
stack4 = ''.join(stack3[-self.trim:]) # take only last records
stack5 = f"Stack {self.terminator} {''.join(stack4)}"
self.stream.write(stack5)
self.stream.write(self.terminator)
self.flush()

日志配置(部分)

LOGGING = {
'handlers': {
'db-console': {
'level': 'DEBUG',
'class': 'settings.local.StackInfoHandler', # Reference the custom handler
'formatter': 'simple',
},
'loggers': {
'django.db.backends': {
'handlers': ['db-console'],
'level': 'DEBUG',
'propagate': False
},
}
}
}

这将只显示 Django 代码库中的堆栈跟踪,如下所示

[2020-05-25 17:49:17,977]: (0.000) INSERT INTO `contacts_contactscount` (`user_id`, `date`, `amount`) VALUES (338, '2020-05-25 17:49:17', 7); args=[338, '2020-05-25 17:49:17', 7]
Stack
File "<project-root>/api/views/contacts.py", line 164, in create
Contact.objects.filter(pk__in=to_delete).delete()
File "<project-root>/<folder>/contacts/models.py", line 54, in delete
create_deletion_log.delay(obj, deleted_timestamp)
File "<project-root>/<folder>/contacts/tasks.py", line 31, in create_deletion_log
contact.save()
File "<project-root>/<folder>/contacts/models.py", line 118, in save
Contact.objects.contacts_added_hook(self.user)
File "<project-root>/<folder>/contacts/models.py", line 67, in contacts_added_hook
current_total = user.profile.contacts_total
File "<project-root>/<folder>/profile/models.py", line 631, in contacts_total
ContactsCount.objects.create(user=self.user, amount=count)

关于python - django数据库查询日志行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53671760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com