gpt4 book ai didi

python日志记录模块没有向文件写入任何内容

转载 作者:IT老高 更新时间:2023-10-28 20:33:02 26 4
gpt4 key购买 nike

我正在尝试编写一个将异常记录到控制台和文件的服务器。我从食谱中提取了一些代码。这里是:

logger = logging.getLogger('server_logger')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('server.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(fh)

此代码完美地记录到控制台,但没有记录到文件中。该文件已创建,但没有写入任何内容。我试过关闭处理程序,但这没有任何作用。冲洗它也不行。我搜索了互联网,但显然我是唯一一个有这个问题的人。有谁知道问题是什么?感谢您的回答。

最佳答案

尝试调用

logger.error('This should go to both console and file')

而不是

logging.error('this will go to the default logger which you have not changed the config of')

关于python日志记录模块没有向文件写入任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15892946/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com