Python logging模块

 1 import logging
 2 '''#1、日志打印
 3 #logging.warning("user [wohaoshuai] attempted wrong password more than 3 times")
 4 #logging.critical("server is down")
 5 
 6 #2、日志记录到文件里
 7 #如果想把日志写到文件里,也很简单
 8 logging.basicConfig(filename="wohaoshuai.log",level=logging.INFO,format="%(asctime)s %(message)s",datefmt="%Y-%m-%d %H:%M:%S")
 9 #其实asctime就是日志生成时间,message就是消息
10 
11 #level级别一共有以下几个:DEBUG(若级别为debug,则不会存到文件中),INFO,WARNING,ERROR,CRITICAL
12 logging.debug("this message should go to the log file")
13 logging.info("so should this")
14 logging.warning("and this,too")
15 #其中下面这句中的level=loggin.INFO意思是,把日志记录级别设置为INFO
16 '''
17 #3、要把日志既生成到屏幕又记录到文件
18 
19 #create logger 创建一个logging对象
20 logger = logging.getLogger("TEST-LOG")
21 logger.setLevel(logging.DEBUG)#相当于设置全局的level为DEBUG,全局的优先级最高
22 
23 
24 #create console handler and set level to debug 创建一个负责屏幕输出的handler
25 ch = logging.StreamHandler()
26 ch.setLevel(logging.DEBUG)
27 
28 #create file handler and set level to warning #创建一个文件handler
29 fh = logging.FileHandler("access.log")
30 fh.setLevel(logging.INFO)#设置为INFO则INFO以下级别全部打印到文件中
31 
32 #create formatter 创建格式
33 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
34 
35 #add formatter to ch and fh 把格式对象赋给屏幕和文件
36 ch.setFormatter(formatter)
37 fh.setFormatter(formatter)
38 
39 #add ch and fh to logger
40 logger.addHandler(ch)
41 logger.addHandler(fh)
42 
43 # "application" code
44 logger.debug("debug message")
45 logger.info("info message")
46 logger.warn("warn message")
47 logger.error("error message")
48 logger.critical("critical message")

 



知识点3中屏幕打印为:

access.log文件中为:

2018-09-11 21:55:26,294 - TEST-LOG - INFO - info message
2018-09-11 21:55:26,294 - TEST-LOG - WARNING - warn message
2018-09-11 21:55:26,294 - TEST-LOG - ERROR - error message
2018-09-11 21:55:26,294 - TEST-LOG - CRITICAL - critical message

 



posted @ 2018-09-11 22:05  Presley  阅读(146)  评论(0编辑  收藏  举报