logging

Posted on 2018-10-17 14:48  shirleyx  阅读(78)  评论(0)    收藏  举报

日志模块 logging

logging模块主要可以根据自定义日志配置,在程序运行的时候将日志打印在终端或者将日志记录在文件中。

logging 支持的日志五个级别:

  • debug():调试级别,一般用于记录程序运行的详细信息
  • info():事件级别,一般用于记录程序运行过程
  • warning():警告级别,一般用于记录程序出现潜在错误的情形
  • error():错误级别,一般用于记录程序出现错误,但不影响整体运行
  • critical():严重错误级别,出现该错误已影响到整体运行

默认级别waring ,默认打印到终端,且打印出比warning级别高的信息,warning,error,critical

 

import logging 
logging.debug('debug information here ')
logging.info('info information here')
logging.warning('warning information here')
logging.error('error information here')
logging.critical('critical information here')
View Code
WARNING:root:warning information here
ERROR:root:error information here
CRITICAL:root:critical information here
Result result

为logging模块指定全局配置,logging.basicConfig()函数

1 import logging
2 logging.basicConfig(level= logging.DEBUG,format='%(name)s %(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
3 datefmt='%Y-%m-%d %H:%M:%S %p')
4 
5 logging.debug('调试debug')
6 logging.info('消息info')
7 logging.warning('警告warn')
8 logging.error('错误error')
9 logging.critical('严重critical')
View Code
root 2018-10-17 10:49:10 AM xueli10162018.py[line:13] DEBUG 调试debug
root 2018-10-17 10:49:10 AM xueli10162018.py[line:14] INFO 消息info
root 2018-10-17 10:49:10 AM xueli10162018.py[line:15] WARNING 警告warn
root 2018-10-17 10:49:10 AM xueli10162018.py[line:16] ERROR 错误error
root 2018-10-17 10:49:10 AM xueli10162018.py[line:17] CRITICAL 严重critical
Result Code

logging.basicCofig() 可用参数:

  1. filename:指定日志文件名
  2. filemode:文件打开方式,在指定filename时使用这个参数,默认值为'a',还可以指定为‘w'
  3. datefmt:指定日期时间格式
  4. level:设置日志级别,默认为logging.WARNING,可选可选 logging.DEBUG logging.INFO logging.WARNING logging.ERROR logging.CRITICAL,注意大写,
  5. stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。
  6. format: 指定日志显示格式,format可以输出很多有用信息,如下所示: 

      格式有:

  •   %(name)s:Logger的名字,并非用户名,详细查看
  •   %(levelno)s:数字形式的日志级别
  •   %(levelname)s:文本形式的日志级别
  •   %(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]
  •   %(filename)s: 打印当前执行程序名
  •  %(funcName)s: 打印日志的当前函数
  •  %(lineno)d: 打印日志的当前行号
  •   %(asctime)s: 打印日志的时间
  •  %(thread)d: 打印线程ID
  •  %(threadName)s: 打印线程名称
  •  %(process)d: 打印进程ID
  •  %(message)s: 打印日志信息

记录日志到文件中:

给logging.basicCofig添加filename ,filemode参数就行。

1 import logging
2 logging.basicConfig(filename='access.log',level= logging.DEBUG,format='%(name)s %(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
3 datefmt='%Y-%m-%d %H:%M:%S %p')
4 
5 logging.debug('调试debug')
6 logging.info('消息info')
7 logging.warning('警告warn')
8 logging.error('错误error')
9 logging.critical('严重critical')
View Code
#此没有终端输出,发现在同级目录生成了一个access.log文件,打开看看,原来日志都已经写进去了,和上面终端输出的一样
root 2018-10-17 10:58:54 AM xueli10162018.py[line:13] DEBUG ����debug
root 2018-10-17 10:58:54 AM xueli10162018.py[line:14] INFO ��Ϣinfo
root 2018-10-17 10:58:54 AM xueli10162018.py[line:15] WARNING ����warn
root 2018-10-17 10:58:54 AM xueli10162018.py[line:16] ERROR ����error
root 2018-10-17 10:58:54 AM xueli10162018.py[line:17] CRITICAL ����critical
Result Code

同输出屏幕和文件中:

eg:现在又有新需求,不能只把日志记录到文件,有些日志信息还想直接在屏幕输出,而且还不影响日志记录到文件,此过程比较复杂,先准备点基础知识

logging四大组件:

  • #logger:产生日志的对象 ,不创建的话默认为root
    
    #Filter:过滤日志的对象,不常有
    
    #Handler:接收日志然后控制打印到不同的地方,FileHandler用来打印到文件中,StreamHandler用来打印到终端
    
    #Formatter对象:可以定制不同的日志格式对象,然后绑定给不同的Handler对象使用,以此来控制不同的Handler的日志格式
import logging
#创建一个logger,默认为root logger
logger = logging.getLogger('xueli09052018.py')
#设置全局log级别为DEBUG,注意全局的优先级最高,实际logger是第一级过滤
logger.setLevel(logging.DEBUG)
#创建终端输出的handler,设置级别为ERROR
ch  = logging.StreamHandler()
ch.setLevel(logging.ERROR)

#创建记录日志的文件handler ,设置级别为info
fh = logging.FileHandler('test.log')
fh.setLevel(logging.INFO)

#设置一个全局的日志格式
fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

#将日志格式应用到终端handler--- ch
ch.setFormatter(fmt)

#将日志格式应用到文件handler--- fh
fh.setFormatter(fmt)

#将终端handler添加到logger
logger.addHandler(ch)

#将文件handler添加到logger
logger.addHandler(fh)

#定义日志message,注意此时时logger,不再是logging
logger.debug('debug debug')
logger.info('info info')
logger.warning('warn warn')
logger.error('error error')
logger.critical('critical critical')
View Code
2018-10-17 11:50:29,185 - xueli09052018.py - ERROR - error error
2018-10-17 11:50:29,185 - xueli09052018.py - CRITICAL - critical critical
终端结果
2018-10-17 11:50:29,185 - xueli09052018.py - INFO - info info
2018-10-17 11:50:29,185 - xueli09052018.py - WARNING - warn warn
2018-10-17 11:50:29,185 - xueli09052018.py - ERROR - error error
2018-10-17 11:50:29,185 - xueli09052018.py - CRITICAL - critical critical
文件结果

 

logger 是第一级过滤,之后才能到handler,可以给logger和handler同时设置level,但是需要注意:

Logger is also the first to filter the message based on a level — if you set the logger to INFO, and all handlers to DEBUG, 
you still won't receive DEBUG messages on handlers — they'll be rejected by the logger itself.
If you set logger to DEBUG, but all handlers to INFO, you won't receive any DEBUG messages either
because while the logger says "ok, process this", the handlers reject it (DEBUG < INFO).
#验证
import logging

form = logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(module)s: %(message)s',datefmt= '%Y-%m-%d %H:%M:%S %P')
ch= logging.StreamHandler()

ch.setFormatter(form)
#ch.setLevel(10)
ch.setLevel(20)

l1=logging.getLogger('root')
#l1.setLevel(20)
l1.setLevel(10)
l1.addHandler(ch)

l1.debug('l1 debug')
View Code

Logger的继承(了解)

import logging

formatter=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p',)

ch=logging.StreamHandler()
ch.setFormatter(formatter)


logger1=logging.getLogger('root')
logger2=logging.getLogger('root.child1')
logger3=logging.getLogger('root.child1.child2')


logger1.addHandler(ch)
logger2.addHandler(ch)
logger3.addHandler(ch)
logger1.setLevel(10)
logger2.setLevel(10)
logger3.setLevel(10)

logger1.debug('log1 debug')
logger2.debug('log2 debug')
logger3.debug('log3 debug')
'''
2017-07-28 22:22:05 PM - root - DEBUG -test:  log1 debug
2017-07-28 22:22:05 PM - root.child1 - DEBUG -test:  log2 debug
2017-07-28 22:22:05 PM - root.child1 - DEBUG -test:  log2 debug
2017-07-28 22:22:05 PM - root.child1.child2 - DEBUG -test:  log3 debug
2017-07-28 22:22:05 PM - root.child1.child2 - DEBUG -test:  log3 debug
2017-07-28 22:22:05 PM - root.child1.child2 - DEBUG -test:  log3 debug
'''
View Code

应用

 

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3