python学习之 logging包

1,logging包

python的一个包,专门用来写日志的。

官方一共划分了6个等级的log类型,分别对应重要性等级50,40,30,20,10,0:

级别排序:CRITICAL > ERROR > WARNING > INFO > DEBUG >NOTSET

2,logging打印日志到控制台(和print效果差不多)

废话不说,直接看代码:

#!coding=utf-8
import logging

logging.basicConfig(level=logging.DEBUG, datefmt='%Y/%m/%d %H:%M:%S',format='%(asctime)s : %(name)s : %(levelname)s : %(message)s')
logger = logging.getLogger("daqing")    #把设置读取到实例中才能用哦

logging.debug('this is the debug message')
logging.info('this is the info message')
logging.warning('this is the warning message')
logging.error('this is the error message')
logging.critical('this is the critical message')
#返回的结果:
2019/05/30 13:21:46 : root : DEBUG : this is the debug message
2019/05/30 13:21:46 : root : INFO : this is the info message
2019/05/30 13:21:46 : root : WARNING : this is the warning message
2019/05/30 13:21:46 : root : ERROR : this is the error message
2019/05/30 13:21:46 : root : CRITICAL : this is the critical message

比较重要的是bascConfig函数,它必须在一开始就进行定义,它的几个参数如下
    # level用于指定最低等级的logging输出,高于或者等于这个等级自动输出,
    # format是指定了字符串格式:包括 asctime、name、levelname、message四个内容(还有别的),分别代表运行时间、模块名称、日志级别、日志内容。
    #datefomt是用于格式化时间
    #filename指定日志文件的名字,这个例子没有带
    #filemode "w"表示清空并且写入,“a"表示追加,一般和上一个参数一块用
    #style 用于指定format的占位符,必须在format前定义,只能是%,{或者$

3,打印日志到文档

#!coding=utf-8
import logging

logging.basicConfig(level=logging.DEBUG,
                    filename='output.log',
                    datefmt='%Y/%m/%d %H:%M:%S',
                    format='%(asctime)s : %(name)s : %(module)s : %(process)d :  %(message)s')  
logger = logging.getLogger("daqing")    #此处logger和logging还是有区别的,logger写出的日志显示的name一项是daqing,而logging显示的name是root
logger.debug('this is the debug message')
logger.info('this is the info message')
logger.warning('this is the warning message')
logging.error('this is the error message')
logging.critical('this is the critical message')
#定义的format是这样的:%(asctime)s : %(name)s : %(module)s : %(process)d :  %(message)s
#返回到output.log中的内容:
2019/05/30 13:23:18 : root : logtest : 4928 :  this is the debug message
2019/05/30 13:23:18 : root : logtest : 4928 :  this is the info message
2019/05/30 13:23:18 : root : logtest : 4928 :  this is the warning message
2019/05/30 13:23:18 : root : logtest : 4928 :  this is the error message
2019/05/30 13:23:18 : root : logtest : 4928 :  this is the critical message

比较重要的是:format内容(常用):

    #%(levelname)s:打印日志级别的名称
    #%(pathname)s:打印当前执行程序的路径
    #%(funcName)s:打印日志的当前函数
    #%(lineno)d:打印日志的当前行号
    #%(process)d:打印进程ID
    #%(message)s:打印日志信息
    #%(module)s:打印模块名称
    #%(name)s: 用户名称

4,同时把日志打印到控制台和日志文件中

#!ccoding=utf-8
import logging

# 第一步,创建一个logger
logger = logging.getLogger("daqing")
logger.setLevel(logging.DEBUG)  # Log等级总开关

# 第二步,创建一个handler,用于写入日志文件,用的是 logging.FileHandler函数,注意它的参数信息
logfile = './logger.txt'
fh = logging.FileHandler(logfile,encoding="utf-8", mode='w')    #mode="a"则是追加
fh.setLevel(logging.INFO)  # 输出到file的log等级的开关

# 第三步,再创建一个handler,用于输出到控制台
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)  # 输出到console的log等级的开关

# 第四步,定义handler的输出格式,控制台和输出到文件的handler可以共用
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
fh.setFormatter(formatter)
ch.setFormatter(formatter)

# 第五步,将logger添加到handler里面,这一步是最重要的,本质上就是为logger添加多个handler
logger.addHandler(fh) 
logger.addHandler(ch)

# 日志
logger.debug('this is a logger debug message')
logger.info('this is a logger info message')
logger.warning('this is a logger warning message')
logger.error('this is a logger error message')
logger.critical('this is
#控制台返回的结果是这样的:
2019-05-30 13:31:46,235 - logtest.py[line:70] - DEBUG: this is a logger debug message
2019-05-30 13:31:46,236 - logtest.py[line:71] - INFO: this is a logger info message
2019-05-30 13:31:46,236 - logtest.py[line:72] - WARNING: this is a logger warning message
2019-05-30 13:31:46,236 - logtest.py[line:73] - ERROR: this is a logger error message
2019-05-30 13:31:46,236 - logtest.py[line:74] - CRITICAL: this is a logger critical message

#logger.txt返回的是这样的:
2019-05-30 13:31:46,236 - logtest.py[line:71] - INFO: this is a logger info message
2019-05-30 13:31:46,236 - logtest.py[line:72] - WARNING: this is a logger warning message
2019-05-30 13:31:46,236 - logtest.py[line:73] - ERROR: this is a logger error message
2019-05-30 13:31:46,236 - logtest.py[line:74] - CRITICAL: this is a logger critical message
#两者虽然共用一个format设置,但是level不同。于是。。。

5,捕获解释器返回的异常信息

#!coding=utf-8
import logging

logging.basicConfig(level=logging.DEBUG, datefmt='%Y/%m/%d %H:%M:%S',format='%(asctime)s : %(name)s : %(levelname)s : %(message)s')
logger = logging.getLogger("daqing")    #把设置读取到实例中才能用哦

logger.info("start")
try:
    a=10/0
except Exception:
    logger.error("hehe",exc_info=True)    #此处打印完“hehe”日志以后,会把try中报错的信息也打印出来
logger.info("finish")
#返回:
2019/05/30 13:42:32 : daqing : INFO : start
2019/05/30 13:42:32 : daqing : ERROR : hehe
Traceback (most recent call last):
  File "D:/python_test/logtest/logtest.py", line 88, in <module>
    a=10/0
ZeroDivisionError: division by zero
2019/05/30 13:42:32 : daqing : INFO : finish

6,logger是可以继承的

logging.basicConfig(level=logging.DEBUG, datefmt='%Y/%m/%d %H:%M:%S',format='%(asctime)s : %(name)s : %(levelname)s : %(message)s')
logger = logging.getLogger("daqing")    #把设置读取到实例中才能用哦

logger.debug('this is a logger debug message')
logger.info('this is a logger info message')
logger.warning('this is a logger warning message')
logger.error('this is a logger error message')
logger.critical('this is a logger critical message')

child_logger=logging.getLogger("daqing.hehe")    #此处的child_logger继承了名字叫daqing的logger的属性
child_logger.setLevel(level=logging.WARNING)   #继承以后修改了部分属性,把level等级改掉了

child_logger.debug('this is a logger debug message')
child_logger.info('this is a logger info message')
child_logger.warning('this is a logger warning message')
child_logger.error('this is a logger error message')
child_logger.critical('this is a logger critical message')
#返回的logger
2019/05/30 13:50:17 : daqing : DEBUG : this is a logger debug message
2019/05/30 13:50:17 : daqing : INFO : this is a logger info message
2019/05/30 13:50:17 : daqing : WARNING : this is a logger warning message
2019/05/30 13:50:17 : daqing : ERROR : this is a logger error message
2019/05/30 13:50:17 : daqing : CRITICAL : this is a logger critical message
#返回的child_logger
2019/05/30 13:50:17 : daqing.hehe : WARNING : this is a logger warning message
2019/05/30 13:50:17 : daqing.hehe : ERROR : this is a logger error message
2019/05/30 13:50:17 : daqing.hehe : CRITICAL : this is a logger critical message
原文地址:https://www.cnblogs.com/0-lingdu/p/10949189.html