Python记录失败 [英] Python Logging is failing

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

问题描述

只是开始查看日志记录模块,并创建了一个虚拟程序来了解记录器,处理程序和格式化程序.这是代码

Just started to look up on the logging module and created a dummy program to understand the logger, handler and formatter. Here is the code

# logging_example.py

import logging
from datetime import datetime
import os

extension = datetime.now().strftime("%d-%b-%Y_%H_%M_%S_%p")
logfile = os.path.join("logs", f"demo_logging_{extension}.txt")

logger = logging.getLogger(__name__)

ch = logging.StreamHandler()
fh = logging.FileHandler(logfile)

ch.setLevel(logging.DEBUG)
fh.setLevel(logging.DEBUG)

formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")

ch.setFormatter(formatter)
fh.setFormatter(formatter)

logger.addHandler(ch)
logger.addHandler(fh)

logger.info("Hello World")

当我执行程序时,日志目录中包含文件,但内容为空,并且屏幕上没有任何内容.我很确定我缺少一些基本的知识,但是:(..

When i execute the program the logs directory has the files but content is empty and nothing gets printed on the screen to. I am pretty sure I am missing something basic but am not able to catch it though :( .

我将不胜感激.

谢谢

推荐答案

您已将日志级别添加到处理程序中,但未添加到记录器中.这意味着,如果记录程序将其传递给处理程序,则处理程序将记录该消息.但是由于记录器阈值较高,因此下降了.

You have added log-level to the handlers but not to the logger. Which means, handler would have logged the message had the logger passed it. But since the logger threshold is higher it got dropped.

查看此链接

还将日志级别添加到记录器.添加处理程序后:

Add log-level to the logger also. After adding the handlers:

logger.setLevel(logging.DEBUG)

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

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