python初级之路-logging模块

python之loggin模块:提供了标准的日志接口,通过该模块可以存储各种格式的日志,loggin日志可以分为debug、info、warning、error和critical五种级别。

 1 #!/usr/bin/env python3
 2 # -*- coding: utf-8 -*-
 3 
 4 import logging
 5 
 6 # 提供了标准的日志接口,通过该模块可以存储各种格式的日志,loggin日志可以分为debug、info、warning、error和critical五种级别。
 7 
 8 """
 9 # 将日志写到日志文件中
10 logging.basicConfig(filename="example.log", level=logging.INFO, format="%(asctime)s %(message)s", datefmt="%m/%d/%Y %I:%M:%S %p")    # 将比info级别高的日志写入到example.log日志文件中,其中: %Y 年 %m 月 %d 日 %H 时 %M 分 %S 秒 %p 时间段
11 logging.debug("This message should go to the log file.")
12 logging.info("So should this.")
13 logging.warning("And this, too.")
14 logging.warning("user [lanten] attempted wrong password more than 3 time.")
15 logging.critical("server is down.")
16 """
17 
18 # 同时将日志打印到屏幕和写到日志文件
19 logger = logging.getLogger("TEST-LOG")    # 定义一个日志对象
20 logger.setLevel(logging.DEBUG)    # 给日志对象定义一个日志级别,全局级别最高
21 
22 sh = logging.StreamHandler()    # 定义一个屏幕输出日志对象
23 sh.setLevel(logging.DEBUG)    # 给屏幕输出日志对象定义一个日志级别
24 
25 fh = logging.FileHandler("access.log", encoding="utf-8")    # 定义一个用于存储日志的文件对象,不设置encoding将会出现中文乱码
26 fh.setLevel(logging.WARNING)    # 给存储日志的文件对象定义一个日志级别
27 
28 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")    # 定义一个日志输出的格式
29 
30 # 将日志输出格式对象赋值给 sh 和 fh 日志对象
31 sh.setFormatter(formatter)
32 fh.setFormatter(formatter)
33 
34 # 再将 sh 和 fh 对象添加到 logger 对象中
35 logger.addHandler(sh)
36 logger.addHandler(fh)
37 
38 # 输出日志
39 logger.debug("这条是Debug日志信息,只输出到屏幕上。")
40 logger.info("这条是Info日志信息,只输出到屏幕上。")
41 logger.warning("这条是Warning日志信息,同时输出到屏幕和日志文件中。")    # 使用warn()方法会提示警告
42 logger.error("这条是Error日志信息,同时输出到屏幕和日志文件中。")
43 logger.critical("这条是Critical日志信息,同时输出到屏幕和日志文件中。")

 

输出结果:

 

format自定义格式,下表中均支持:

posted @ 2020-10-21 17:15  Zombie☠️  阅读(123)  评论(0)    收藏  举报