首页 > 编程语言 > 详细

python中logging模块的使用方法

时间:2020-03-05 14:12:45      阅读:82      评论:0      收藏:0      [点我收藏+]

  python中logging提供了一组便利的函数,用来做简单的日志。它们分别是 debug()、 info()、 warning()、 error() 和 critical()。

    logging以严重程度递增排序:

    DEBUG:详细信息,一般只在调试问题时使用

    INFO:证明事情按预期工作

    WARNING:某些没有预料到的时间提示,或者在将来可能会出现的问题提示。例如:磁盘空间不足,但是软件还是会照常运作

    ERROR:由于更严重的问题,软件已不能执行一些功能了

    CRITICAL:严重错误,表明软件已不能继续运行了

    严重级别排序:CRITICAL>ERROR>WARNING>INFO>DEBUG

    默认等级是WARNING

1.输出日志到控制台

 1 import logging
 2 
 3 # 创建一个日志收集器,指定具体名称的记录器
 4 my_log_collector = logging.getLogger("mylog")
 5 
 6 # 设置日志收集器等级
 7 my_log_collector.setLevel("DEBUG")  # 等级参数必须大写
 8 
 9 # 设置日志输出格式
10 formater = logging.Formatter(%(asctime)s [%(filename)s-->line:%(lineno)d] 11 - %(levelname)s: %(message)s)
12 
13 # 定义输出到控制台
14 output_console = logging.StreamHandler()
15 
16 # 设置输出到控制台日志格式
17 output_console.setFormatter(formater)
18 
19 # 设置输出到控制台日志等级
20 output_console.setLevel("INFO")  # 等级参数必须大写
21 
22 # 把输出到控制台,添加到日志收集器中
23 my_log_collector.addHandler(output_console)
24 
25 # 需要输出的日志等级
26 my_log_collector.debug(输出日志信息为debug)
27 my_log_collector.info(输出日志信息为info)
28 my_log_collector.warning(输出日志信息为warning)
29 my_log_collector.error(输出日志信息为error)
30 my_log_collector.critical(输出日志信息为critical)

技术分享图片

 

2.输出日志到具体路径的文件夹下

 1 import logging
 2 # 创建一个日志收集器,指定具体名称的记录器
 3 my_log_collector = logging.getLogger("mylog")
 4 
 5 # 设置日志收集器等级
 6 my_log_collector.setLevel("DEBUG")  # 等级参数必须大写
 7 
 8 # 设置日志输出格式
 9 formater = logging.Formatter(%(asctime)s [%(filename)s-->line:%(lineno)d] 10 - %(levelname)s: %(message)s)
11 
12 # 定义输出到具体路径下的文件夹,使用R/r进行格式化,输出格式为【utf-8】
13 output_file = logging.FileHandler(filename=r"E:\testfile\test.log", encoding=utf-8)
14 
15 # 把日志格式添加到输出文件对象下
16 output_file.setFormatter(formater)
17 
18 # 设置输出到文件夹下的日志等级
19 output_file.setLevel("INFO")  # 等级参数必须大写
20 
21 # 把输出到控制台,添加到日志收集器中
22 my_log_collector.addHandler(output_file)
23 
24 # 需要输出的日志等级
25 my_log_collector.debug(输出日志信息为debug)
26 my_log_collector.info(输出日志信息为info)
27 my_log_collector.warning(输出日志信息为warning)
28 my_log_collector.error(输出日志信息为error)
29 my_log_collector.critical(输出日志信息为critical)

技术分享图片

 

python中logging模块的使用方法

原文:https://www.cnblogs.com/pengjt/p/12419805.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!