码迷,mamicode.com
首页 > 其他好文 > 详细

logging模块

时间:2018-07-11 20:07:24      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:get   color   hid   level   enc   模块   cal   isp   module   

简单的屏幕打印:

技术分享图片简单的屏幕打印

打印的结果为:  


WARNING:root: This msg is warning
ERROR:root: This msg is error
CRITICAL:root: This msg is critical

这个只能打印,如果要写入文件,先升级下代码:

技术分享图片
 1 import logging
 2 
 3 logging.basicConfig(level=logging.DEBUG,
 4                     format="%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s",
 5                     datefmt=%a, %d %b %Y %H:%M:%S,
 6                     filename=test.log,
 7                     filemode=a)
 8 logging.debug("This msg is debug")
 9 logging.info("This msg is info")
10 logging.warning("This msg is warning")
11 logging.error("This msg is error")
12 logging.critical("This msg is critical")
打印和写入日志文件同时进行

在日志中写入的结果为:


 

Wed, 11 Jul 2018 17:37:02 os_module.py[line:16] DEBUG This msg is debug
Wed, 11 Jul 2018 17:37:02 os_module.py[line:17] INFO This msg is info
Wed, 11 Jul 2018 17:37:02 os_module.py[line:18] WARNING This msg is warning
Wed, 11 Jul 2018 17:37:02 os_module.py[line:19] ERROR This msg is error
Wed, 11 Jul 2018 17:37:02 os_module.py[line:20] CRITICAL This msg is critical

 

现在来个新需求,在屏幕打印全部信息,在文件中写入Info一上的,在升级一次代码

技术分享图片
 1 import logging
 2 
 3 logger = logging.getLogger()
 4 fh = logging.FileHandler(test.log,encoding=utf-8)
 5 sh = logging.StreamHandler()
 6 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
 7 
 8 logger.addHandler(fh)
 9 logger.addHandler(sh)
10 logger.setLevel(logging.DEBUG)
11 
12 fh.setFormatter(formatter)
13 sh.setFormatter(formatter)
14 fh.setLevel(logging.INFO)
15 
16 logging.debug("This msg is debug")
17 logging.info("This msg is info")
18 logging.warning("This msg is warning")
19 logging.error("This msg is error")
20 logging.critical("This msg is critical")
满足你的需求

日志记录:


 

2018-07-11 17:50:09,410 - root - INFO - This msg is info
2018-07-11 17:50:09,410 - root - WARNING - This msg is warning
2018-07-11 17:50:09,410 - root - ERROR - This msg is error
2018-07-11 17:50:09,411 - root - CRITICAL - This msg is critical

 

pingmu :


 

2018-07-11 17:50:09,410 - root - DEBUG This msg is debug
2018-07-11 17:50:09,410 - root - INFO - This msg is info
2018-07-11 17:50:09,410 - root - WARNING - This msg is warning
2018-07-11 17:50:09,410 - root - ERROR - This msg is error
2018-07-11 17:50:09,411 - root - CRITICAL - This msg is critical

 

logging模块

标签:get   color   hid   level   enc   模块   cal   isp   module   

原文地址:https://www.cnblogs.com/linga/p/9295949.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!