python - 常用模块 - logging模块

python主要是通过logging模块来进行日志处理

很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误、警告等信息输出,python的logging模块提供了标准的日志接口,

你可以通过它存储各种格式的日志,logging的日志可以分为 debug(), info(), warning(), error(), critical() 5个级别,

  日志级别:
    DEBUG
    INFO
    WARNING
    ERROR
    CRITICAL
等级依次提高(打印的信息越来越少,DEBUG最详细)

 1 日志格式:
 2     %(name)s            Logger的名字(默认root)
 3     %(levelno)s         字形式的日志级别 依次为:
 4                         DEBUG:10  INFO:20  WARNING:30  ERROR:40  CRITICAL:50
 5     %(levelname)s       文本形式的日志级别
 6     %(pathname)s        调用日志输出函数的模块的完整路径名,可能没有
 7     %(filename)s        调用日志输出函数的模块的文件名
 8     %(module)s          调用日志输出函数的模块名   
 9     %(message)s         用户输出的消息
10     %(funcName)s        调用日志输出函数的函数名
11     %(lineno)d          调用日志输出函数的语句所在的代码行
12     %(created)f         当前时间,用UNIX标准的表示时间的浮 点数表示
13     %(relativeCreated)d    输出日志信息时的,自Logger创建以 来的毫秒数
14     %(asctime)s         字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
15     %(thread)d          线程ID。可能没有
16    %(threadName)s      线程名。可能没有
17     %(process)d         进程ID。可能没有

日志模块使用:

  1、最简单用法,打印到屏幕( 不用print,自带打印)

1 import logging
2 logging.warning('user [root] attempted wrong password more than 3 times')
3 logging.critical('server is down') 

#想要debug()、info() 或 error() 跟上面一样,添加上就是了

  2、设置时间

1 import logging
2 logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
3 logging.warning('is when this event was logged.')

  3、把日志写到文件

1 import logging
2 
3 logging.basicConfig(filename='./file/logging.log',level=logging.DEBUG,format='%(asctime)s  %(name)s - %(levelname)s ->%(levelno)s :  %(message)s ', datefmt='%Y-%m-%d %H:%M:%S')
4 logging.debug('This message should go to the log file')
5 logging.info('So should this')
6 logging.warning('And this, too')
7 logging.error('And this, too')
8 logging.critical('And this, too')

文件内容:

    2017-04-04 17:14:10 root - DEBUG ->10 : This message should go to the log file
    2017-04-04 17:14:10 root - INFO ->20 : So should this
    2017-04-04 17:14:10 root - WARNING ->30 : And this, too
    2017-04-04 17:14:10 root - ERROR ->40 : And this, too
    2017-04-04 17:14:10 root - CRITICAL ->50 : And this, too

  4、把日志同时写到文件和打印到屏幕 

 1 '''
 2 Python 使用logging模块记录日志涉及四个主要类,使用官方文档中的概括最为合适:
 3 
 4      logger提供了应用程序可以直接使用的接口;
 5          Logger.setLevel(lel):指定最低的日志级别,低于lel的级别将被忽略。debug是最低的内置级别,critical为最高
 6          Logger.addFilter(filt)、Logger.removeFilter(filt):添加或删除指定的filter
 7          Logger.addHandler(hdlr)、Logger.removeHandler(hdlr):增加或删除指定的handler
 8          Logger.debug()、Logger.info()、Logger.warning()、Logger.error()、Logger.critical():可以设置的日志级别
 9 
10      handler将(logger创建的)日志记录发送到合适的目的输出;
11           Handler.setLevel(lel):指定被处理的信息级别,低于lel级别的信息将被忽略
12           Handler.setFormatter():给这个handler选择一个格式
13           Handler.addFilter(filt)、Handler.removeFilter(filt):新增或删除一个filter对象
14 
15      filter提供了细度设备来决定输出哪条日志记录;
16 
17      formatter决定日志记录的最终输出格式。
18 '''
19 import logging
20 
21 #创建logger
22 logger = logging.getLogger('XT-LOG')
23 logger.setLevel(logging.DEBUG)  
24      #设置全局的日志级别(全局的优先级高于局部的但是若局部的在全局之上,则保存局部的)
25      
26 #创建一个console handler,并且设置其日志级别为debug
27 ch = logging.StreamHandler()
28 ch.setLevel(logging.DEBUG)
29 
30 #创建一个file handler,并且设置其日志级别为warning
31 fh = logging.FileHandler('./file/logging.log')
32 fh.setLevel(logging.WARNING)
33 
34 #创建一个formatter(格式)
35 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s',datefmt='%Y-%m-%d %H:%M:%S')
36 
37 #把formatter添加到console handler和file handler
38 ch.setFormatter(formatter)
39 fh.setFormatter(formatter)
40 
41 #把console handler和file handler添加到logger
42 logger.addHandler(ch)
43 logger.addHandler(fh)
44 
45 #设置错误消息
46 logger.debug('debug message')
47 logger.info('info message')
48 logger.warning('warning message')
49 logger.error('error message')
50 logger.critical('critical message')

以上输出到屏幕结果:

    2017-04-08 16:12:49 - XT-LOG - DEBUG - debug message
    2017-04-08 16:12:49 - XT-LOG - INFO - info message
    2017-04-08 16:12:49 - XT-LOG - WARNING - warning message
    2017-04-08 16:12:49 - XT-LOG - ERROR - error message
    2017-04-08 16:12:49 - XT-LOG - CRITICAL - critical message

 

posted on 2017-04-08 16:14  txowner  阅读(182)  评论(0编辑  收藏  举报