python的logging模块

python的logging模块

一、日志的级别

日志级别 含义
debug 详细信息,典型地调试问题时会感兴趣。
info 证明事情按预期工作。
warning 表明发生了一些意外,或者不久的将来会发生问题(如‘磁盘满了’)。软件还是在正常工作。
error 由于更严重的问题,软件已不能执行一些功能了。
fatal 严重错误,表明软件已不能继续运行了。
例子一:

 
 
 
 
 
 
 
 
 
 
 
1
"""
2
v1: 练习python的日志生成
3
"""
4

5
import logging  # 导入logging模块,学习改模块
6

7
logging.debug("这个是debug级别的日志")
8
logging.info("这个是info级别的日志")
9
logging.warning("这个是warning级别的日志")
10
logging.error("这个是error级别的日志")
11
logging.fatal("这个是fatal级别的日志")
12

13
# 默认配置下,只输出warning及以上级别的日志
14
# 默认情况下,logging模块将日志打印到屏幕上(stdout),
15
# 日志级别为WARNING(即只有日志级别高于WARNING的日志信息才会输出),日志格式如下图所示:
16
"""
17
WARNING:root:这个是warning级别的日志
18
ERROR:root:这个是error级别的日志
19
CRITICAL:root:这个是fatal级别的日志
20
"""
21

 
 
例二:简单配置log

 
 
 
 
 
 
 
 
 
 
 
1
"""
2
v1: 练习python的日志生成,并配置一下log
3
"""
4
import logging
5

6
logging.basicConfig(filename='logfile.log', filemode='a', level=logging.DEBUG)
7
"""
8
basicConfig()函数的基本用法
9
filename  Specifies that a FileHandler be created, using the specified
10
              filename, rather than a StreamHandler.
11
    filemode  Specifies the mode to open the file, if filename is specified
12
              (if filemode is unspecified, it defaults to 'a').
13
    format    Use the specified format string for the handler.
14
    datefmt   Use the specified date/time format.
15
    style     If a format string is specified, use this to specify the
16
              type of format string (possible values '%', '{', '$', for
17
              %-formatting, :meth:`str.format` and :class:`string.Template`
18
              - defaults to '%').
19
    level     Set the root logger level to the specified level.
20
                CRITICAL = 50
21
                FATAL = CRITICAL
22
                ERROR = 40
23
                WARNING = 30
24
                WARN = WARNING
25
                INFO = 20
26
                DEBUG = 10
27
                NOTSET = 0
28

29
    stream    Use the specified stream to initialize the StreamHandler. Note
30
              that this argument is incompatible with 'filename' - if both
31
              are present, 'stream' is ignored.
32
    handlers  If specified, this should be an iterable of already created
33
              handlers, which will be added to the root handler. Any handler
34
              in the list which does not have a formatter assigned will be
35
              assigned the formatter created in this function.
36

37
"""
38
logging.debug("debug hahaha")
39
logging.info("info hahaha")
40
logging.warning("warning hahaha")
41
logging.error("error hahaha")
42
logging.fatal("fatal hahaha")
43

44
# 此时屏幕未输出任何东西,但是多了一个logfile.log文件
 
 

二、重要概念

 
1、Logger
记录器,暴露了应用程序代码能直接使用的接口。
Logger是一个树形层级结构,在使用接口debug,info,warn,error,critical之前必须创建Logger实例,即创建一个记录器,
如果没有显式的进行创建,则默认创建一个root logger,并应用默认的日志级别(WARN),处理器Handler(StreamHandler,
即将日志信息打印输出在标准输出上),和格式化器Formatter(默认的格式即为第一个简单使用程序中输出的格式)。
<wiz_code_mirror>
 
 
 
 
 
 
 
 
 
 
 
1
# 创建方法: 
2
logger = logging.getLogger(logger_name)
 
 
 

创建Logger实例后,可以使用以下方法进行日志级别设置,增加处理器Handler。

  • logger.setLevel(logging.ERROR) # 设置日志级别为ERROR,即只有日志级别大于等于ERROR的日志才会输出
  • logger.addHandler(handler_name) # 为Logger实例增加一个处理器
  • logger.removeHandler(handler_name) # 为Logger实例删除一个处理器

 
 
 
 
 
 
 
 
 
 
 
1
"""
2
通过调用 Logger 类(以下称为 loggers , 记录器)的实例来执行日志记录。 每个实例都有一个名称,它们在概念上以点(句点)作为分隔符排列在命名空间的层次结构中。 
3
例如,名为 'scan' 的记录器是记录器 'scan.text' ,'scan.html' 和 'scan.pdf' 的父级。 记录器名称可以是你想要的任何名称,并指示记录消息源自的应用程序区域。
4
"""
5

6
"""
7
Logger is also the first to filter the message based on a level — if you set the logger to INFO, 
8

9
and all handlers to DEBUG, 
10
you still won't receive DEBUG messages on handlers — they'll be rejected by the logger itself. 
11
If you set logger to DEBUG, but all handlers to INFO, 
12
you won't receive any DEBUG messages either — because while the logger says "ok, process this", 
13
the handlers reject it (DEBUG < INFO).
14
"""
 
 
2、Handler
 处理器,将(记录器产生的)日志记录发送至合适的目的地。
3、Formatter
格式化器,指明了最终输出中日志记录的布局。

 
 
 
 
 
 
 
 
 
 
 
1
可在logging.basicConfig()函数中通过具体参数来更改logging模块默认行为,可用参数有
2
filename:用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。
3
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
4
format:指定handler使用的日志显示格式。 
5
datefmt:指定日期时间格式。 
6
level:设置rootlogger(后边会讲解具体概念)的日志级别 
7
stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。
8

9

10

11
#格式
12
%(name)s:Logger的名字,并非用户名,详细查看
13

14
%(levelno)s:数字形式的日志级别
15

16
%(levelname)s:文本形式的日志级别
17

18
%(pathname)s:调用日志输出函数的模块的完整路径名,可能没有
19

20
%(filename)s:调用日志输出函数的模块的文件名
21

22
%(module)s:调用日志输出函数的模块名
23

24
%(funcName)s:调用日志输出函数的函数名
25

26
%(lineno)d:调用日志输出函数的语句所在的代码行
27

28
%(created)f:当前时间,用UNIX标准的表示时间的浮 点数表示
29

30
%(relativeCreated)d:输出日志信息时的,自Logger创建以 来的毫秒数
31

32
%(asctime)s:字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
33

34
%(thread)d:线程ID。可能没有
35

36
%(threadName)s:线程名。可能没有
37

38
%(process)d:进程ID。可能没有
39

40
%(message)s:用户输出的消息
 
 
4、Filter
过滤器,提供了更好的粒度控制,它可以决定输出哪些日志记录。
 

三、以配置文件的形式配置logging


 
 
 
 
 
 
 
 
 
 
 
1
# 文件名:mylog.conf
2
[loggers] # 配置了两个logger对象
3
keys=root,simpleExample 
4

5
[handlers]   # 配置了两个handler对象,一个是控制台输出,另一用文件输出
6
keys=consoleHandler,fileHandler
7

8
[formatters] # 配置了一个格式化器
9
keys=simpleFormatter
10

11
[logger_root] # root这个logger,配的等级是DEBUG
12
level=DEBUG
13
handlers=consoleHandler   # 
14

15
[logger_simpleExample] # simple这个loger配置的等级也是DEBUG
16
level=DEBUG
17
handlers=fileHandler
18
qualname=simpleExample
19
propagate=0            # 通常,我们都需要显示的指定propagate的值为0,防止日志记录向上层logger传递。这里就是防止像上层root_loger传递
20

21
[handler_consoleHandler]
22
class=StreamHandler   # 
23
level=DEBUG
24
formatter=simpleFormatter
25
args=(sys.stdout,)
26

27
[handler_fileHandler]
28
class=FileHandler             # The FileHandler class, located in the core logging package, 、
29
  # sends logging output to a disk file. It inherits the output functionality from StreamHandler.
30
level=DEBUG
31
format=simpleFormatter
32
args=('mylog.log',)
33

34

35
[formatter_simpleFormatter]
36
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
37
datefmt=
 
 
Nobody knows it better than me.
原文地址:https://www.cnblogs.com/dadaizi/p/13060436.html