国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

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

2019-11-14 17:05:31
字體:
來源:轉載
供稿:網友

一、默認日志配置

在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 loggingfrom django.http import HttpResponseRedirect,HttpResponse, Http404from django.shortcuts import render_to_response, get_object_or_404from django.template import RequestContextlog=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/pythonimport osimport sysimport timesys.path.append("..")import confimport loggingimport logging.handlerstry:    import curses    curses.setupterm()except:    curses = Nonedefault_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.instanceclass 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 osSMARTCLOUD_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 MessageLogLOG = 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://m.survivalescaperooms.com/starof/p/4702026.html有問題歡迎與我討論,共同進步。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 江安县| 彝良县| 康保县| 吴川市| 张掖市| 得荣县| 荔浦县| 广水市| 廊坊市| 宜君县| 册亨县| 蓬莱市| 平凉市| 会东县| 广元市| 海南省| 黑水县| 库车县| 鸡东县| 大丰市| 刚察县| 常宁市| 土默特右旗| 青海省| 邵东县| 上蔡县| 紫阳县| 哈尔滨市| 中卫市| 如皋市| 偃师市| 乌苏市| 灵川县| 焦作市| 安庆市| 卢龙县| 汕尾市| 扎鲁特旗| 庆城县| 土默特右旗| 阿克|