日志模块logging使用心得

在应用程序使用中,日志输出对应用维护人员、开发人员判断程序的问题起重要作用。

那么在python中如何定义程序的日志输出? 推荐使用日志模块logging

 

需求:实现日志内容输出在文件中和控制器中

 1 import logging
 2 
 3 # 日志配置
 4 logger = logging.getLogger("ys_monitor")
 5 logger.setLevel(logging.DEBUG)  # 全局
 6 formatter = logging.Formatter('%(asctime)s - %(levelname)s -%(module)s:  %(message)s')   # 日志格式
 7 
 8 fh = logging.FileHandler(filename_path)  # 文件输出
 9 fh.setLevel(logging.DEBUG)
10 fh.setFormatter(formatter)  # 应用给文件
11 logger.addHandler(fh)  # 把文件句柄交给logger接口执行
12 
13 #ch = logging.StreamHandler()  # 屏幕输出
14 #ch.setLevel(logging.DEBUG)
15 #ch.setFormatter(formatter)  # 应用给屏幕
16 #logger.addHandler(ch)  # 把屏幕句柄交给logger接口执行
View Code

模块级函数
logging.getLogger([name]):返回一个logger对象,如果没有指定名字将返回root logger
logging.debug()、logging.info()、logging.warning()、logging.error()、logging.critical():设定root logger的日志级别
Logger.setLevel(lel):指定最低的日志级别,低于lel的级别将被忽略。debug是最低的内置级别,critical为最高

Logger.debug()、Logger.info()、Logger.warning()、Logger.error()、Logger.critical():可以设置的日志级别

 

 

Formatters

Formatter对象设置日志信息最后的规则、结构和内容,默认的时间格式为%Y-%m-%d %H:%M:%S,下面是Formatter常用的一些信息

%(name)s

Logger的名字

%(levelno)s

数字形式的日志级别

%(levelname)s

文本形式的日志级别

%(pathname)s

调用日志输出函数的模块的完整路径名,可能没有

%(filename)s

调用日志输出函数的模块的文件名

%(module)s

调用日志输出函数的模块名

%(funcName)s

调用日志输出函数的函数名

%(lineno)d

调用日志输出函数的语句所在的代码行

%(created)f

当前时间,用UNIX标准的表示时间的浮 点数表示

%(relativeCreated)d

输出日志信息时的,自Logger创建以 来的毫秒数

%(asctime)s

字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒

%(thread)d

线程ID。可能没有

%(threadName)s

线程名。可能没有

%(process)d

进程ID。可能没有

%(message)s

用户输出的消息

 

需求:对于文件日志输出,随着时间的增长,日志内容越来越多,文件越来越大,不利于以后的查看。需要将文件按时间分割。

配置文件

 1 ###############################################
 2 [loggers]
 3 keys=root,wj
 4 
 5 [logger_root]
 6 level=DEBUG
 7 handlers=hand01
 8 
 9 [logger_wj]
10 handlers=hand02
11 qualname=wj
12 propagate=0
13 
14 ###############################################
15 [handlers]
16 keys=hand01,hand02
17 
18 [handler_hand01]
19 class=StreamHandler
20 level=DEBUG
21 formatter=formatter02
22 args=(sys.stdout,)
23 
24 [handler_hand02]
25 class=handlers.TimedRotatingFileHandler
26 level=DEBUG
27 formatter=formatter02
28 args=('./log/mixh5monitor.log','midnight',1,30)
29 
30 ###############################################
31 [formatters]
32 keys=formatter01,formatter02
33 
34 [formatter_formatter01]
35 format=%(asctime)s - %(process)d - %(module)s - %(levelname)s - %(message)s
36 datefmt=%Y-%m-%d %H:%M:%S
37 
38 [formatter_formatter02]
39 format=%(asctime)s - %(process)d - %(module)s - %(levelname)s - %(message)s
40 datefmt=
View Code

引入配置文件代码,单独放入一个log_config.py文件

1 import logging
2 import logging.config
3 
4 LOGCONF_FILENAME = "./etc/logging.conf"
5 logging.config.fileConfig(LOGCONF_FILENAME)
6 logger = logging.getLogger('wj')
View Code

logging.handlers.RotatingFileHandler
这 个Handler类似于上面的FileHandler,但是它可以管理文件大小。当文件达到一定大小之后,它会自动将当前日志文件改名,然后创建 一个新的同名日志文件继续输出。比如日志文件是chat.log。当chat.log达到指定的大小之后,RotatingFileHandler自动把 文件改名为chat.log.1。不过,如果chat.log.1已经存在,会先把chat.log.1重命名为chat.log.2。。。最后重新创建 chat.log,继续输出日志信息。它的构造函数是:
RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]])
其中filename和mode两个参数和FileHandler一样。
maxBytes用于指定日志文件的最大文件大小。如果maxBytes为0,意味着日志文件可以无限大,这时上面描述的重命名过程就不会发生。
backupCount用于指定保留的备份文件的个数。比如,如果指定为2,当上面描述的重命名过程发生时,原有的chat.log.2并不会被更名,而是被删除。


logging.handlers.TimedRotatingFileHandler
这 个Handler和RotatingFileHandler类似,不过,它没有通过判断文件大小来决定何时重新创建日志文件,而是间隔一定时间就 自动创建新的日志文件。重命名的过程与RotatingFileHandler类似,不过新的文件不是附加数字,而是当前时间。它的构造函数是:
TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]])
其中filename参数和backupCount参数和RotatingFileHandler具有相同的意义。
interval是时间间隔。
when参数是一个字符串。表示时间间隔的单位,不区分大小写。它有以下取值:
S 秒
M 分
H 小时
D 天
W 每星期(interval==0时代表星期一)
midnight 每天凌晨

其它py文件引入log_config.py文件写日志方法

1 import log_config
2 
3 log_config.logger.debug('debug')
4 log_config.logger.info('info')
View Code

 

Python多进程log日志切分错误的解决方案

 1 #修改后的代码,从30行开始引用文件锁,保证进程间的原子性。
 2 import time
 3 import os
 4 import fcntl
 5 import struct
 6 
 7 from logging.handlers import TimedRotatingFileHandler
 8 
 9 class MultiProcessTimedRotatingFileHandler(TimedRotatingFileHandler):
10 
11     def doRollover(self):
12         """
13         do a rollover; in this case, a date/time stamp is appended to the filename
14         when the rollover happens.  However, you want the file to be named for the
15         start of the interval, not the current time.  If there is a backup count,
16         then we have to get a list of matching filenames, sort them and remove
17         the one with the oldest suffix.
18         """
19         #if self.stream:
20         #    self.stream.close()
21         # get the time that this sequence started at and make it a TimeTuple
22         t = self.rolloverAt - self.interval
23         if self.utc:
24             timeTuple = time.gmtime(t)
25         else:
26             timeTuple = time.localtime(t)
27         dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple)
28         #if os.path.exists(dfn):
29         #    os.remove(dfn)
30         lockdata = struct.pack('hhllhh', fcntl.F_WRLCK, 0, 0, 0, 0, 0)
31         fcntl.fcntl(self.stream, fcntl.F_SETLKW, lockdata)
32         if not os.path.exists(dfn) and os.path.exists(self.baseFilename):
33             os.rename(self.baseFilename, dfn)
34             with open(self.baseFilename, 'a'):
35                 pass
36         if self.backupCount > 0:
37             # find the oldest log file and delete it
38             #s = glob.glob(self.baseFilename + ".20*")
39             #if len(s) > self.backupCount:
40             #    s.sort()
41             #    os.remove(s[0])
42             for s in self.getFilesToDelete():
43                 os.remove(s)
44         #print "%s -> %s" % (self.baseFilename, dfn)
45         if self.stream:
46             self.stream.close()
47         self.mode = 'a'
48         self.stream = self._open()
49         currentTime = int(time.time())
50         newRolloverAt = self.computeRollover(currentTime)
51         while newRolloverAt <= currentTime:
52             newRolloverAt = newRolloverAt + self.interval
53         #If DST changes and midnight or weekly rollover, adjust for this.
54         if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc:
55             dstNow = time.localtime(currentTime)[-1]
56             dstAtRollover = time.localtime(newRolloverAt)[-1]
57             if dstNow != dstAtRollover:
58                 if not dstNow:  # DST kicks in before next rollover, so we need to deduct an hour
59                     newRolloverAt = newRolloverAt - 3600
60                 else:           # DST bows out before next rollover, so we need to add an hour
61                     newRolloverAt = newRolloverAt + 3600
62         self.rolloverAt = newRolloverAt
View Code

 

参考:

http://my.oschina.net/leejun2005/blog/126713

http://blog.sina.com.cn/s/blog_3fe961ae01016upf.html

http://lightthewoods.me/2013/11/18/Python%E5%A4%9A%E8%BF%9B%E7%A8%8Blog%E6%97%A5%E5%BF%97%E5%88%87%E5%88%86%E9%94%99%E8%AF%AF%E7%9A%84%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88/

http://www.jianshu.com/p/d615bf01e37b#

posted @ 2016-01-28 11:21  shhnwangjian  阅读(657)  评论(0编辑  收藏  举报