简单的错误日志消息在django [英] simple error log message in django

查看:96
本文介绍了简单的错误日志消息在django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在1.3中通过Django的日志记录机制设置了错误的电子邮件。当发生错误时,它会发送一封电子邮件。但是,当我记录一个简单的错误消息时,它的格式是奇怪的,我不知道为什么。



例如,在我的应用程序中有一个条件, t存在于我想知道的数据库中,但是我有一个合适的默认值可以正常工作。因此,我想要一些电子邮件发送给我一些信息;



如果我这样做:



logger.error(数据库中没有操作%s,actionX)的费用。



日志文件中的信息是正常的,但电子邮件真的缺少一些信息。这是主题行:

  [Django]错误:测试这个爵士乐%s 

然后身体:

 

请求repr()不可用

我的问题是,我如何获得A)在主题中显示的值和B)在身体中获得一些实际的相关信息....像行号或类似的东西。

解决方案您需要确认两件事:


  1. 您想使用Python的内置日志记录系统发送电子邮件,

  2. 您没有记录常规异常,因此内置的发送电子邮件的机制将不起作用,因为它取决于要传递的异常类型的对象和要存储在追溯中的东西。 / li>

无论如何,不​​可能!

  LOGGING = {
...
'处理程序':{
...
'my_special_mail _handler':{
'level':'ERROR',
'filters':[],
'class':'myapp.loggers.MyEmailHandler',
'include_html' :


'logger':{
...
'my_special_logger':{
'handlers':['控制台','my_special_mail_handler'],
'level':'DEBUG',
'propagate':True,
},
}
}

MY_RECIPIENTS =((人名,email@example.com),)





然后,有你的特殊记录类MyEmailHandler:


$ b $从django.utils.log导入b $ pre> $ code从django.core.mail.message导入AdminEmailHandler
导入EmailMultiAlternatives
从django.conf导入设置

class MyEmailHandler(AdminEmailHandler):

def emit(self,re
如果不是getattr(设置,MY_RECIPIENTS,无):
return
subject = self.format_subject(record.getMessage())
message = getattr(record ,email_body,record.getMessage())
mail = EmailMultiAlternatives(u'%s%s'%(settings.EMAIL_SUBJECT_PREFIX,subject),
message,settings.SERVER_EMAIL,[a [1]对于一个设置.MY_RECIPIENTS],)
mail.send(fail_silently = False)

现在,您可以创建一个特殊的日志记录条目,通过电子邮件发送并以这种方式输出到终端:

  import logging 
logger = logging.getLogger(my_special_logger)
error = logger.makeRecord(
logger.name,logging.ERROR,0,0,
u主题:有些错误发生
无,无,,无,

error.email_body = msg
logger.handle(错误)
pre>

并且使东西变得容易,使用效用函数:

  import logging 
def my_log(msg,body,level = logging.ERROR):
logger = logging.getLogger(my_special_logger)
error = logger.makeRecord(
logger.name,level,0,0,
u主题:有些错误发生,
无,无,,无,

error.email_body = msg
logger.handle(错误)


I've got error emails setup via Django's logging mechanism in 1.3. It sends me a nice email when an error happens. However, when I log a simple error message it's being formatted oddly and I'm not sure why.

For example, there's a condition in my app where if something doesn't exist in the DB I want to know about, but I have a suitable default value that will work fine. Thus, I want an email sent to me with some info; it's not necessarily happening on an Exception.

If I do something like this:

logger.error("fee did not exist in the database for action %s", "actionX")

The information in the logfile is fine, but the email is really lacking some information. Here's the subject line:

[Django] ERROR: Test this jazz %s

And then the body:

None

Request repr() unavailable

My question is, how do I get A) the value to show up in the subject and B) get some actual, relevant information in the body....like line number or something like that.

解决方案

You need to acknowledge two things:

  1. You want to send an email using Python's builtin logging system and
  2. You are not logging a regular exception so the builtin mechanism for sending emails won't work since it's depending on an exception type-like object to be passed and stuff to be stored in a traceback.

Anyways, not impossible!

LOGGING = {
   ...
   'handlers': {
        ...
        'my_special_mail_handler': {
            'level': 'ERROR',
            'filters': [],
            'class': 'myapp.loggers.MyEmailHandler',
            'include_html': False,
        },
    },
    'loggers': {
        ...
        'my_special_logger': {
            'handlers': ['console', 'my_special_mail_handler'],
            'level': 'DEBUG',
            'propagate': True,
        },
    }
}

MY_RECIPIENTS = (("Name of person", "email@example.com"),)

...that stuff is merged into your settings.

Then, there's your special logging class, MyEmailHandler:

from django.utils.log import AdminEmailHandler
from django.core.mail.message import EmailMultiAlternatives
from django.conf import settings

class MyEmailHandler(AdminEmailHandler):

    def emit(self, record):
        if not getattr(settings, "MY_RECIPIENTS", None):
            return
        subject = self.format_subject(record.getMessage())
        message = getattr(record, "email_body", record.getMessage())
        mail = EmailMultiAlternatives(u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject),
                    message, settings.SERVER_EMAIL, [a[1] for a in settings.MY_RECIPIENTS],)
        mail.send(fail_silently=False)

Now you're able to create a special logging entry that's both emailed and output to the terminal this way:

import logging
logger = logging.getLogger("my_special_logger")
error = logger.makeRecord(
    logger.name, logging.ERROR, 0, 0,
    u"Subject: Some error occured",
    None, None, "", None,
)
error.email_body = msg
logger.handle(error)

and to make stuff easy, use a utility function:

import logging
def my_log(msg, body, level=logging.ERROR):
    logger = logging.getLogger("my_special_logger")
    error = logger.makeRecord(
        logger.name, level, 0, 0,
        u"Subject: Some error occured",
        None, None, "", None,
    )
    error.email_body = msg
    logger.handle(error)

这篇关于简单的错误日志消息在django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆