小编use*_*775的帖子

Python 日志记录创建空文件

我正在使用 python 的日志记录工具。如果有要记录的内容,我只想创建一个日志文件。换句话说,如果没有要记录的内容,则不应创建任何日志文件。

立刻

logging.basicConfig( filename=filename_log, level=logging.DEBUG, mode='w')
Run Code Online (Sandbox Code Playgroud)

运行时,会创建一个空的日志文件。我尝试在退出之前删除它:

if ( os.stat( filename_log ).st_size == 0 ): os.remove( filename_log)
Run Code Online (Sandbox Code Playgroud)

这给出了一条错误消息:

WindowsError: [Error 32] The process cannot access the file because it is being used by another process
Run Code Online (Sandbox Code Playgroud)

所以我想之前应该做一些其他的事情。

那么,有没有办法在不编写自己的日志记录程序的情况下不生成空日志文件?

简而言之:

logging.basicConfig( filename=filename_log, level=logging.DEBUG, mode='w')
logging.debug('This message should go to the log file')
Run Code Online (Sandbox Code Playgroud)

确实记录正确,但如果没有要记录的内容,则会提供一个空文件。和

with open( filename_log, 'w') as logfile:
    logging.basicConfig( stream=logfile, level=logging.DEBUG)
Run Code Online (Sandbox Code Playgroud)

给出: ValueError: I/O operation on closed file

python logging

6
推荐指数
1
解决办法
2915
查看次数

标签 统计

logging ×1

python ×1