记录setLevel,它如何工作 [英] logging setLevel, how it works

查看:135
本文介绍了记录setLevel,它如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

记录howto文档中,有一个示例:

import logging

# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# add formatter to ch
ch.setFormatter(formatter)

# add ch to logger
logger.addHandler(ch)

为什么我应该将LoggerStreamHandler的水平两次设置为logging.DEBUG?

Why I should set the level to logging.DEBUG twice, for Logger, and for the StreamHandler?

我了解ch.setLevel(logging.DEBUG)将为流处理程序设置调试级别.但是将级别设置为记录器有什么作用?这个水平反映在哪里?

I understand ch.setLevel(logging.DEBUG) will set the debug level for the stream handler. But what the effect is of setting the level to logger? Where this level is reflected?

如果将级别更改为例如LoggerStreamHandler,则会得到相同的控制台输出.

I get the same console output if I change the level to, for example, INFO either to the Logger or to the StreamHandler.

也就是说:

...........
logger.setLevel(logging.INFO)
............
ch.setLevel(logging.DEBUG)

在控制台中提供的输出与

gives the same output in console than

...........
logger.setLevel(logging.DEBUG)
............
ch.setLevel(logging.INFO)

推荐答案

可以在那里进行微调(您可以有多个处理程序,并且每个处理程序可以设置不同的级别)-您不能在处理程序上安全地设置级别,将导致它处理所有消息(也称为NOTSET级别),并将级别过滤留给记录器.

It's there for fine-tuning (you can have multiple handlers, and each could have different levels set) — you can safely not set level on the handler, which will cause it to process all messages (a.k.a. NOTSET level), and leave level filtering to the logger.

记录器也是第一个基于级别过滤消息的记录器-如果将记录器设置为INFO,而所有处理程序都设置为DEBUG,则仍然不会在处理程序上收到DEBUG消息-记录器将拒绝它们本身.如果将记录器设置为DEBUG,但是将所有处理程序都设置为INFO,则您也不会收到任何DEBUG消息-因为当记录器说确定,请处理"时,处理程序会拒绝它(DEBUG< INFO).

Logger is also the first to filter the message based on a level — if you set the logger to INFO, and all handlers to DEBUG, you still won't receive DEBUG messages on handlers — they'll be rejected by the logger itself. If you set logger to DEBUG, but all handlers to INFO, you won't receive any DEBUG messages either — because while the logger says "ok, process this", the handlers reject it (DEBUG < INFO).

这篇关于记录setLevel,它如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆