python - 为什么这个 Pythonlogging.exception 不起作用?

标签 python django logging

我有一段 Python 代码,如果引发 IOError 异常,它应该将错误消息和关联的堆栈跟踪写入我的 Django 日志文件。不过,我发现错误和堆栈跟踪被写入我的控制台,而不是我的日志文件。我检查了 Django 日志配置,没有发现问题。我将 LOG_LEVEL 设置为 DEBUG,并且有一个“日志文件”处理程序。有人看出我做错了什么吗?

谢谢!

# photo.py
import os
import logging
logger = logging.getLogger(__name__)
import shutil

pvt_photo_path = "/www/proj/pvt/photo1.jpg"
pub_photo_path = "/www/proj/pub/photo1.jpg"
try:
    shutil.move(pvt_photo_path, pub_photo_path)
except IOError as e:
    logging.exception("Couldn't move photo %s" % pvt_photo_path)


# settings.py
LOG_LEVEL = 'DEBUG'
LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'standard': {
            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt' : "%d/%b/%Y %H:%M:%S"
        },
    },
    'handlers': {
        'null': {
            'level':'DEBUG',
            'class':'django.utils.log.NullHandler',
        },
        'logfile': {
            'level':LOG_LEVEL,
            'class':'logging.handlers.RotatingFileHandler',
            'filename': '/var/log/proj/proj.log',
            'maxBytes': 50000,
            'backupCount': 2,
            'formatter': 'standard',
        },
        'database_logfile': {
            'level':LOG_LEVEL,
            'class':'logging.handlers.RotatingFileHandler',
            'filename': '/var/log/proj/database.log',
            'maxBytes': 50000,
            'backupCount': 2,
            'formatter': 'standard',
        },
        'console':{
            'level':LOG_LEVEL,
            'class':'logging.StreamHandler',
            'formatter': 'standard'
        },
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        },
    },
    'loggers': {
        'django': {
            'handlers':['logfile', 'database_logfile', 'console', 'mail_admins'],
            'propagate': True,
            'level':'DEBUG',
        },
        'django.request': {
           'handlers': ['logfile', 'mail_admins'],
           'level': 'ERROR',
           'propagate': False,
        },
        'django.db.backends': {
            'handlers': ['database_logfile'],
            'level': 'DEBUG',
            # Logging messages are not passed to the handlers of ancestor loggers.
            'propagate': False,
        },
        '': {
            'handlers': ['console'],
            'level': 'DEBUG',
        },
    }
}


root: ERROR: Couldn't move photo for user "test_user"
Traceback (most recent call last):
  File "/www/proj/classes/photo.py", line 1167, in make_photo_public
    shutil.move(pvt_gall_photo_path, pub_gall_photo_path)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 301, in move
    copy2(src, real_dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 130, in copy2
    copyfile(src, dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 82, in copyfile
    with open(src, 'rb') as fsrc:
IOError: [Errno 2] No such file or directory: '/www/proj/pvt/photo1.jpg'
--------------------- >> end captured logging << ---------------------

最佳答案

看起来您正在访问logging模块的exception方法。您确实想访问 logging 模块的 logger 实例。所以,试试这个:

try:
    shutil.move(pvt_photo_path, pub_photo_path)
except IOError as e:
    logger.exception("Couldn't move photo %s" % pvt_photo_path)

此类事情在 logging 模块的 documentation 中进行了描述。 .

但是,您设置问题的方式使我无法直接调试它。您发布的代码不使用您提供的 LOG_LEVELLOGGING 变量,不导入 Django,并且根本不设置日志记录处理程序。

所以,我假设您实际上没有完成代码中发布的内容,只是遗漏了适当创建和使用文件处理程序的部分。如果您包含一个损坏代码的简单演示,这将会有所帮助,以便我们可以重现您的错误:How do I ask a good question?

关于python - 为什么这个 Pythonlogging.exception 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31546615/

相关文章:

python - 使用 Conda 在 Python 3.5 上安装 OpenCV

django - 向 Wagtail 仪表板添加按钮

使用 Selenium 的 Django 测试未加载固定装置

.net - ServiceConfiguration.cscfg 中的自定义/嵌套 XML 设置

logging - 作业历史记录日志文件

Python 日志记录与写入文件

python - 如何从在C层进行内存分配的python脚本中将float *数组传递给C方法

Python Pandas - Fillna(method=ffill) 导致 NameError

Python:使用 %x(语言环境)格式化的日期与预期不符

python - DatabaseError : current transaction is aborted, 命令在事务 block 结束之前被忽略?