首页 > 代码库 > 日志处理之logging模块

日志处理之logging模块

1 日志级别:
2    CRITICAL: CRITICAL,
3     ERROR: ERROR,
4     WARN: WARNING,
5     WARNING: WARNING,
6     INFO: INFO,
7     DEBUG: DEBUG,
8     NOTSET: NOTSET,
import logging
logging.warning("user [wy] attempted wrong password more than 3 times")
logging.critical("server is down")
输出:
WARNING:root:user [wy] attempted wrong password more than 3 times
CRITICAL:root:server is down

如何把日志写入到文件中?
import logging
logging.basicConfig(filename="example.log",level=logging.INFO) #filename后面是日志文件名,level为INFO级别,日志文件会记录INFO级别以上的日志
logging.warning("user [wy] attempted wrong password more than 3 times")
logging.info("show this")
logging.debug("this is erro")
logging.critical("server is down")
生成一个新的文件example.log
example.log记录:
WARNING:root:user [wy] attempted wrong password more than 3 times
INFO:root:show this
CRITICAL:root:server is down

日志级别:debug<info<warning<critical

 

 1 怎么在日志中加入时间?
 2 import logging
 3 logging.basicConfig(filename="example.log",level=logging.INFO,format="%(asctime)s %(message)s",datefmt="%m/%d/%Y %I:%M:%S %p") #注意大小写
 4 logging.warning("user [wy] attempted wrong password more than 3 times")
 5 logging.info("show this")
 6 logging.debug("this is erro")
 7 logging.critical("server is down")
 8 
 9 example.log显示:
10 10/20/2016 08:49:32 PM user [wy] attempted wrong password more than 3 times
11 10/20/2016 08:49:32 PM show this
12 10/20/2016 08:49:32 PM server is down

 

日志处理之logging模块