Django 日志

import logging
from logging.handlers import TimedRotatingFileHandler

log = logging.getLogger(loggerName)

formatter = logging.Formatter('%(name)-12s %(asctime)s level-%(levelname)-8s thread-%(thread)-8d %(message)s')   # 每行日志的前缀设置
fileTimeHandler = TimedRotatingFileHandler(BASIC_LOG_PATH + filename, "S", 1, 10)

fileTimeHandler.suffix = "%Y%m%d.log"  #设置 切分后日志文件名的时间格式 默认 filename+"." + suffix 如果需要更改需要改logging 源码
fileTimeHandler.setFormatter(formatter)
logging.basicConfig(level = logging.INFO)
fileTimeHandler.setFormatter(formatter)
log.addHandler(fileTimeHandler)
try:
     log.error(msg)
except Exception, e:
    print "writeLog error"
finally:
   log.removeHandler(fileTimeHandler)

 

值 interval的类型
S 秒
M 分钟
H 小时
D 天
W 周
midnight 在午夜

 

Django程序使用logging输出的基本设置

要让Django程序正确得利用logging模块输出日志,首先需要在settings.py中配置好logging参数:
loggin.basicConfig(
level = logging.DEBUG,
format = '%(asctiome)s %(levelname)s %(module)s.%(funcName)s Line:%(lineno)d%(message)s',
)
logging.basicConfig是logging模块提供的简便配置logging参数的方法。经过以上的配置,在Django程序中只需要通过logging.debug,logging.info等方法就可以输出日志了。logging.DEBUG及以上级别的日志都会直接输出到django运行时当前命令窗口,而在生产环境下,只需要相应的提高logging输出级别就可以控制日志输出的内容,避免输出过多日志内容。(关于logging级别和logging的基本知识请参考pydoc) 在本地调试使用manage.py runserver的时候,logging内容就会直接出现在console里。
 

输出日志到文件

以上的基本设置只能让日志直接输出到命令行窗口。需要把日志输出到文件保存的话最简便的方法是这样
logging.basicConfig(
level = logging.DEBUG,
format = '%(asctiome)s %(levelname)s %(module)s.%(funcName)s Line:%(lineno)d%(message)s',
filename = '/path/to/logfile/filelog.log',
)
在logging.basicConfig方法中,只要指定了filename,那么日志就会直接输出到指定的文件了。
 

按日期循环保存日志文件

在生产环境下,不仅需要把日志写到文件,通常还需要把日志文件按日期分割保存。这样的任务用logging模块也很容易做到。在生产环境的settings.py里使用如下设置:
root = logging.getLogger()
if len(root.handlers) == 0 #避免重复
level = logging.INFO
filename = '/path/to/logfile/filelog.log'
format = '%(asctiome)s %(levelname)s %(module)s.%(funcName)s Line:%(lineno)d%(message)s'
hdlr = TimedRotatingFileHandler(filename,"midnight",1,5)
fmt = Formatter(format)
hdlr.setFormatter(fmt)
root.addHandler(hdlr)
root.setLevel(level)
在这里使用了logging模块预定义的TimedRotatingFileHandler类,在每天半夜滚动日志文件,而最多保留5个以往的日志文件。由于需要指定特殊的Handler,所以这里不能使用logging.basicConfig的简便方法。
posted @ 2012-06-27 07:10  SophiaTang  阅读(1945)  评论(0编辑  收藏  举报