在 PyCharm 中运行时记录 basicConfig 不创建日志文件? [英] Logging basicConfig not creating log file when I run in PyCharm?

查看:166
本文介绍了在 PyCharm 中运行时记录 basicConfig 不创建日志文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在终端中运行下面的代码时,它会创建一个日志文件

When I run below code in terminal its create a log file

import logging 
logging.basicConfig(filename='ramexample.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

但是当我在 PyCharm 中运行相同的代码(使用不同的 filename='ram.log')时,它不会创建任何日志文件.为什么?

but when I run the same code (with different filename='ram.log') in PyCharm it's not creating any log file. Why?

import logging 
logging.basicConfig(filename='ram.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

我需要做什么才能使用 PyCharm 创建日志文件?

What I have to do to create a log file with PyCharm?

推荐答案

我遇到了同样的问题,发现以前在这里提供的答案都不起作用.也许这个问题早在 Ramnath Reddy 就已经解决了,但我在网上的任何地方都找不到正确的答案.

I encountered same issue and found none of the answers previously provided here would work. Maybe this issue had been solved long ago to Ramnath Reddy, but I could not find the correct answer anywhere online.

幸运的是,我通过在 logging.basicConfig() 之前添加以下几行从同事的代码中找到了解决方案.

Luckily, I found a solution from a colleague's code by adding the following lines before logging.basicConfig().

# Remove all handlers associated with the root logger object.
for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)

试试看是否对遇到同样问题的人有帮助.

Try and see if it helps for whomever had the same issue.

Python 3.8:新选项 force 可用于在调用 basicConfig() 时自动删除根处理程序.
例如:

Python 3.8: A new option, force, has been made available to automatically remove the root handlers while calling basicConfig().
For example:

logging.basicConfig(filename='ramexample.log', level=logging.DEBUG, force=True)`

参见 logging.basicConfig 参数:

force:如果此关键字参数指定为 true,则在执行其他参数指定的配置之前,将删除并关闭附加到根记录器的任何现有处理程序.

force: If this keyword argument is specified as true, any existing handlers attached to the root logger are removed and closed, before carrying out the configuration as specified by the other arguments.

这篇关于在 PyCharm 中运行时记录 basicConfig 不创建日志文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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