当我在终端下面运行代码时,它会创建一个日志文件
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')
Run Code Online (Sandbox Code Playgroud)
但是当我在pycharm中运行相同的代码(使用不同的filename ='ram.log')时,它不会创建任何日志文件.为什么?
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')
Run Code Online (Sandbox Code Playgroud)
我需要做什么来创建pycharm的日志文件?
小智 33
我遇到了同样的问题,发现以前提供的答案都没有用.也许很久以前这个问题已经解决了Ramnath Reddy,但我无法在网上找到正确答案.
幸运的是,我之前通过添加以下行找到了同事代码的解决方案logging.basicConfig().
删除与根记录器对象关联的所有处理程序.
Run Code Online (Sandbox Code Playgroud)for handler in logging.root.handlers[:]: logging.root.removeHandler(handler)
试着看看它是否对同样的问题有帮助.
noo*_*bie 16
我不记得我在哪里得到的,否则我会提供一个链接。但是前段时间在 jupyter notebooks 中使用时遇到了同样的问题,这修复了它:
import logging
logger = logging.getLogger()
fhandler = logging.FileHandler(filename='mylog.log', mode='a')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fhandler.setFormatter(formatter)
logger.addHandler(fhandler)
logger.setLevel(logging.DEBUG)
Run Code Online (Sandbox Code Playgroud)
马克西玛斯是对的。文件路径是相对于执行环境的。但是,您可以尝试动态路径解析方法,而不是写下绝对路径:
filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ram.log')
logging.basicConfig(filename=filename, level=logging.DEBUG)
Run Code Online (Sandbox Code Playgroud)
这假设ram.log与包含上述代码的目录位于同一目录中(这__file__就是用于的原因)。
小智 7
为什么这个错误发生的答案是这样:
调用 to
basicConfig()应该在任何调用之前出现debug(),info()等等。
如果这样做,basicConfig 将无法创建和写入新文件。我logging.info()之前就在这里打过电话logging.basicConfig()。
别:
import logging
logging.info("root") # call to info too early
logging.basicConfig(filename="rec/test.log", level=logging.DEBUG) # no file created
Run Code Online (Sandbox Code Playgroud)

这确实使用 Py 终端在 pycharm 终端内创建一个日志。您需要检查终端所在的位置(在 Windows 上尝试 dir 或在 linux/mac 上尝试 pwd)。不要只放入 ram.log,而是使用您希望文件出现的位置的完整文件路径。例如
logging.basicConfig(filename='/Users/Donkey/Test/ram.log', level=logging.DEBUG)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11990 次 |
| 最近记录: |