将django.request记录到文件而不是控制台 [英] Logging django.request to file instead of console
问题描述
我正在尝试将Django settings.py
配置为正确使用python日志记录工具,但我偶然发现了一个相当奇怪的问题:
I am trying to configure my django settings.py
to properly use the python logging facility but I've stumbled upon a rather strange problem:
即使阅读了 docs ,我也可以找不到如何将控制台打印的调试请求行从Django重定向到我指定的文件的方法;以下是我的日志记录配置的一部分.
Even after reading the docs, I simply can't find out how to redirect the console printed debug request lines from Django to a file I've specified; Below is part of my logging configuration.
LOGGING = {
'version': 1,
'formatters': {
'simple': {
'format': '%(levelname)s %(message)s'
},
}
'handlers': {
'file_http': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': r'C:\mysystem-http.log',
'formatter': 'verbose'
}
},
'loggers': {
'django.request': {
'handlers': ['file_http'],
'level': 'DEBUG',
'propagate': False
}
}
}
我一直看到以下格式的控制台打印行:
I keep seeing my console print line of the following format:
[19/Dec/2014 11:48:03] "POST /api/v1/ HTTP/1.1" 200 10
如何使用日志记录工具将这些重定向到文件?
How may I redirect these to a file using the logging facility?
预先感谢
推荐答案
manage.py runserver
未将日志系统用于[19/Dec/2014 11:48:03] "POST /api/v1/ HTTP/1.1" 200 10
之类的消息.取而代之的是,runserver使用sys.stderr(对于其他消息使用sys.stdout).如果确实需要将其重定向到文件,则可以覆盖sys.stderr settings.py.示例-将sys.stderr记录到文件和控制台:
manage.py runserver
is not using logging system for messages like [19/Dec/2014 11:48:03] "POST /api/v1/ HTTP/1.1" 200 10
. Instead of this, runserver uses sys.stderr (and sys.stdout for others messages). If you really need to redirect this to file you can override sys.stderr settings.py. Example - logging sys.stderr to file and console:
import sys
class Logger(object):
def __init__(self):
self.console = sys.stderr
self.file = open("runserver.log", "a", 0)
def write(self, msg):
self.console.write(msg)
self.file.write(msg)
sys.stderr = Logger()
在写入方法中,您还可以使用日志记录系统通过LOGGING设置来处理此问题.
In write method you can use logging system to handle this by LOGGING settings as well.
更新:
在Django 1.10中,runserver输出通过日志记录: https://docs.djangoproject.com/zh/dev/releases/1.10/#runserver-output-goes-through-logging
In Django 1.10, runserver output goes through logging: https://docs.djangoproject.com/en/dev/releases/1.10/#runserver-output-goes-through-logging
这篇关于将django.request记录到文件而不是控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!