您所在的位置:小祥子 » 编程 » Python » 正文

django1.4日志模块配置及使用

时间:2015-08-05 编辑:starof 来源:CnBlogs

一、默认日志配置

在django 1.4中默认有一个简单的日志配置,如下

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = { 
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }   
    },  
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }   
    },  
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },  
    }   
}

可以看出默认的‘disable_existing_loggers’值为False。

默认没有定义formatters。

字典中,组结束没有加逗号,所以在增加时需要写上。

二、简单例子

1、配置settings.py中LOGGING

增加下面绿色部分内容配置。

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': '%(levelname)s %(asctime)s %(message)s'
        },
    },
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        },
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        },
        'test1_handler':{
            'level':'DEBUG',
            'class':'logging.handlers.RotatingFileHandler',
            'filename':'/yl/smartcloud/smartcloud/lxytest.log',
            'formatter':'standard',
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
        'test1':{
            'handlers':['test1_handler'],
            'level':'INFO',
            'propagate':False
        },
    }
}

配置中level,filename之类的可自定义,需要几个文件就配置几个handler和logger。

2、使用

  • 导入logging
  • 如果在用到log的view.py中,想使用test1这个日志,就写:
    • log=logging.getLogger('test1')
    • log.error()
  •  在日志内容中传递变量,log.error("Get html error, %s" % (e))
#!/usr/bin/python
#-*- coding: UTF-8 -*-

import logging
from django.http import HttpResponseRedirect,HttpResponse, Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext


log=logging.getLogger('test1')

def getHtml(request,arg):
    try:
        url=request.path
        url=url[1:]
        return render_to_response(url,RequestContext(request))
    except Exception,e:
        #log.error("Get html error, %s" % (e))
        log.error("日志内容")
        raise Http404

 

使用变量后的log如下:

三、封装django logging模块

django自带的logging模块也是可以用的,如果要求更高,希望加一些自定义的颜色,格式等,可进行下面操作。

1、将log封装成一个单独的app

[root@yl-web-test log]# django-admin.py startapp log
[root@yl-web-test log]# ls
__init__.py  models.py  tests.py  views.py

2、创建一个log.py,内容如下

#!/usr/bin/python

import os
import sys
import time
sys.path.append("..")
import conf
import logging
import logging.handlers

try:
    import curses
    curses.setupterm()
except:
    curses = None

default_logfile = getattr(conf,'SMARTCLOUD_LOGFILE')class Singleton(type):
    """Singleton Metaclass"""
    def __init__(cls,name,bases,dic):
        super(Singleton,cls).__init__(name,bases,dic)
        cls.instance = None
    def __call__(cls, *args, **kwargs):
        if cls.instance is None:
            cls.instance = super(Singleton,cls).__call__(*args,**kwargs)
        return cls.instance

class MessageFormatter(logging.Formatter):
    def __init__(self,color,*args,**kwargs):
        logging.Formatter.__init__(self,*args,**kwargs)
        self._color=color
        if color and curses:
            fg_color = unicode(curses.tigetstr("setaf") or\
                                        curses.tigetstr("setf") or "", "ascii")

            self._colors={
                    logging.DEBUG: unicode(curses.tparm(fg_color,2),"ascii"),
                    logging.INFO: unicode(curses.tparm(fg_color,6),"ascii"),
                    logging.WARNING: unicode(curses.tparm(fg_color, 3), "ascii"),
                    logging.ERROR: unicode(curses.tparm(fg_color, 5), "ascii"),
                    logging.FATAL: unicode(curses.tparm(fg_color, 1), "ascii"),
                    }
            self._normal = unicode(curses.tigetstr("sgr0"), "ascii")

    def format(self,record):
        try:
            record.message = record.getMessage()
        except Exception, e:
            record.message = "Bad message (%r): %r" % (e, record.__dict__)
        record.asctime = time.strftime("%Y/%m/%d %H:%M:%S",\
                                                            self.converter(record.created))
        prefix = '[%(levelname)-8s %(asctime)s] ' % record.__dict__
        if self._color and curses:
            prefix = (self._colors.get(record.levelno, self._normal) +\
                                                                        prefix + self._normal)
        formatted = prefix + record.message
        if record.exc_info:
            if not record.exc_text:
                record.exc_text = self.formatException(record.exc_info)
        if record.exc_text:
            formatted = formatted.rstrip() + "\n" + record.exc_text
        return formatted.replace("\n", "\n    ")

class MessageLog(object):
    __metaclass__ = Singleton

    def __init__(self, logfile=default_logfile,):
        self._LEVE = {1:logging.INFO, 2:logging.WARNING, 3:logging.ERROR,\
                                                      4:logging.DEBUG, 5:logging.FATAL}
        self.loger = logging.getLogger()
        self._logfile = logfile
        self.init()

    def init(self):
        if not os.path.exists(self._logfile):
            os.mknod(self._logfile)
        handler = logging.handlers.RotatingFileHandler(self._logfile)
        handler.setFormatter(MessageFormatter(color=True))
        self._handler = handler
        self.loger.addHandler(handler)

    def INFO(self,msg,leve=1):
        self.loger.setLevel(self._LEVE[leve])
        self.loger.info(msg)

    def WARNING(self, msg, leve=2):
        self.loger.setLevel(self._LEVE[leve])
        self.loger.warning(msg)

    def ERROR(self, msg, leve=3):
        self.loger.setLevel(self._LEVE[leve])
        self.loger.error(msg)

    def DEBUG(self, msg, leve=4):
        self.loger.setLevel(self._LEVE[leve])
        self.loger.debug(msg)

    def FATAL(self, msg, leve=5):
        self.loger.setLevel(self._LEVE[leve])
        self.loger.fatal(msg)

conf.py是一个配置文件,在log app同目录,里面配置了log文件目录。

import os

SMARTCLOUD_LOGFILE='/yl/smartcloud/log/smartcloud.log'

3、测试

在log.py结果加上一段测试代码如下:

if __name__ == "__main__":
    LOG = MessageLog()
    str1 = "aaaaaaaa"
    str2 = "bbbbbbbbbb"
    LOG.INFO("#%s###################################"
                        "@@@@%s@@@@@@@@@@@" %(str1,str2))
    LOG.WARNING("####################################")
    LOG.ERROR("####################################")
    LOG.DEBUG("####################################")
    LOG.FATAL("####################################")

测试结果如下:

4、在view中使用

usage e.g:

from log import MessageLog
LOG = MessageLog('your log file by full path')
or LOG = MessageLog()
default logfile name is '/yl/smartcloud/log/smartcloud.log'

LOG.INFO('some message')
LOG.WARNING('some message')
LOG.ERROR('some message')
LOG.DEBUG('some message')
LOG.FATAL('some message')

本文作者starof,因知识本身在变化,作者也在不断学习成长,文章内容也不定时更新,为避免误导读者,方便追根溯源,请诸位转载注明出处:http://www.cnblogs.com/starof/p/4702026.html有问题欢迎与我讨论,共同进步。

关键词:日志 使用