Python基础17模块-logging模块

1.logging模块配置

  • 默认日志级别为warning,可通过basicConfig()函数修改
  • debug < info < warning < error < critical
import logging
logging.basicConfig(
    level = logging.DEBUG,
    filename='loger.log',
    filemode='w',
    format = '%(asctime)s [%(lineno)d] %(message)s'
)
print(logging.debug('HELLO'))
  • basicConfig 参数介绍

  • format参数中可能用到的格式化串:

2.logging同时输出到屏幕跟你文件的方法

# logging.getLogger()创建对象可以加参数,不加默认创建的对象为根节点root;
# 如果logger1 = logging.getLogger("test"),logger1 = logging.getLogger("test")创建logger对象,名字一样对应的是同一个对象,修改日志等级会互相影响;
# 如果同时存在父节点跟子节点,则打印子节点日志的时候,会把父节点的日志也打印一遍,相当于两次,对父节点去除打印功能可解决;
import logging
logger = logging.getLogger()
fh = logging.FileHandler("test_log","w")#不写默认文件写入方式为a,也可以自己指定
ch = logging.StreamHandler()
fm = logging.Formatter("%(asctime)s %(message)s")
fh.setFormatter(fm)
ch.setFormatter(fm)
logger.addHandler(fh)
logger.addHandler(ch)
logger.setLevel(logging.DEBUG)
print(logger.debug("hello"))

猜你喜欢

转载自www.cnblogs.com/josie930813/p/9829188.html