日志处理之logging模块

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了日志处理之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模块的主要内容,如果未能解决你的问题,请参考以下文章

Python之日志处理(logging模块)

Python之日志处理(logging模块)

python日志之logging模块--理解

我的Android进阶之旅NDK开发之在C++代码中使用Android Log打印日志,打印出C++的函数耗时以及代码片段耗时详情

日志处理之logging模块

常用python日期日志获取内容循环的代码片段