简体   繁体   English

如何在Django中配置Python日志记录模块?

[英]How do I configure the Python logging module in Django?

I'm trying to configure logging for a Django app using the Python logging module. 我正在尝试使用Python logging模块为Django应用程序配置日志logging I have placed the following bit of configuration code in my Django project's settings.py file: 我在Django项目的settings.py文件中放置了以下配置代码:

import logging
import logging.handlers
import os
date_fmt = '%m/%d/%Y %H:%M:%S'
log_formatter = logging.Formatter(u'[%(asctime)s] %(levelname)-7s: %(message)s (%(filename)s:%(lineno)d)', datefmt=date_fmt)
log_dir = os.path.join(PROJECT_DIR, "var", "log", "my_app")
log_name = os.path.join(log_dir, "nyrb.log")
bytes = 1024 * 1024   # 1 MB
if not os.path.exists(log_dir):
  os.makedirs(log_dir)
handler = logging.handlers.RotatingFileHandler(log_name, maxBytes=bytes, backupCount=7)
handler.setFormatter(log_formatter)
handler.setLevel(logging.DEBUG)
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger().addHandler(handler)
logging.getLogger(__name__).info("Initialized logging subsystem")

At startup, I get a couple Django-related messages, as well as the "Initialized logging subsystem", in the log files, but then all the log messages end up going to the web server logs ( /var/log/apache2/error.log , since I'm using Apache), and use the standard log format (not the formatter I designated). 在启动时,我在日志文件中收到了一些与Django相关的消息以及“初始化日志子系统”,但是随后所有日志消息最终都进入了Web服务器日志( /var/log/apache2/error.log (因为我使用的是Apache),并使用标准的日志格式(而不是我指定的格式化程序)。 Am I configuring logging incorrectly? 我是否配置了错误的日志记录?

Kind of anti-climactic, but it turns out there was a third-party app installed in the project that had its own logging configuration that was overriding the one I set up (it modified the root logger, for some reason -- not very kosher for a Django app!). 有点抗高潮,但事实证明,该项目中安装了一个第三方应用程序,该应用程序具有自己的日志记录配置,该配置取代了我设置的日志记录配置(出于某些原因,它修改了根记录器-不太符合犹太标准) Django应用!)。 Removed that code and everything works as expected. 删除了该代码,一切正常。

I used this with success (although it does not rotate ): 我成功地使用了它(尽管它不会旋转 ):

# in settings.py
import logging
logging.basicConfig(
    level = logging.DEBUG,
    format = '%(asctime)s %(levelname)s %(funcName)s %(lineno)d \
              \033[35m%(message)s\033[0m', 
    datefmt = '[%d/%b/%Y %H:%M:%S]',
    filename = '/tmp/my_django_app.log',
    filemode = 'a'
)

I'd suggest to try an absolute path, too. 我建议也尝试绝对路径。

See this other answer . 看到其他答案 Note that settings.py is usually imported twice, so you should avoid creating multiple handlers. 请注意,settings.py通常被导入两次,因此您应避免创建多个处理程序。 Better logging support is coming to Django in 1.3 (hopefully), but for now you should ensure that if your setup code is called more than once, there are no adverse effects. 希望在1.3中为Django提供更好的日志记录支持,但是现在您应该确保如果多次调用设置代码,不会有不利影响。

I'm not sure why your logged messages are going to the Apache logs, unless you've (somewhere else in your code) added a StreamHandler to your root logger with sys.stdout or sys.stderr as the stream. 我不确定为什么您的登录消息会进入Apache日志,除非您(在代码中的其他位置)将sys.stdoutsys.stderr作为流添加了StreamHandler到根记录器中。 You might want to print out logging.getLogger().handlers just to see it's what you'd expect to see. 您可能希望打印出logging.getLogger().handlers只是为了查看它是您期望看到的。

I guess logging stops when Apache forks the process. 我猜想日志将在Apache分叉进程时停止。 After that happened, because all file descriptors were closed during daemonization, logging system tries to reopen log file and as far as I understand uses relative file path: 在那之后,由于所有文件描述符都在守护进程中关闭,因此日志记录系统会尝试重新打开日志文件,据我所知,它使用相对文件路径:

log_dir = os.path.join(PROJECT_DIR, "var", "log", "my_app")
log_name = os.path.join(log_dir, "nyrb.log")

But there is no “current directory” when process has been daemonized. 但是,在守护进程后没有“当前目录”。 Try to use absolute log_dir path. 尝试使用绝对log_dir路径。 Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM