简体   繁体   English

Python在日志记录配置文件中设置文件模式

[英]Python set filemode in logging configuration file

I am trying to config the loggers in a text configuration file using Python. 我正在尝试使用Python在文本配置文件中配置记录器。 Here is partial content: 这是部分内容:

[logger_root]
handlers=result
level=NOTSET

[handler_result]
class=handlers.TimedRotatingFileHandler
interval=midnight
backupCount=5
formatter=simple
level=DEBUG
args=('result_log.txt')

I would like to rewrite the log file every time I run the system. 我想在每次运行系统时重写日志文件。 But not know how to set it in the file. 但是不知道如何在文件中设置它。 I try this but fails: 我尝试这样做,但失败了:

args=('result_log.txt',filemode='w')

A lot of articles talk about how to set it from the Python code. 许多文章讨论如何从Python代码进行设置。 But I would like to set it in the file. 但是我想在文件中设置它。 How to do it? 怎么做? Thanks. 谢谢。

======================================= ======================================

Edit: I can write some info into the log file 'result_log.txt' by: 编辑:我可以通过以下方式将一些信息写入日志文件“ result_log.txt”:

result_logger = logging.getLogger('result')
result_logger.debug("info to write")

But I can only "append" to the file. 但是我只能“附加”到该文件。 I would like to rewrite the file every time i run. 我想每次运行都重写文件。

You can use either of the two methods:- 您可以使用以下两种方法之一:

  1. Backup the old log file and create a new file using RotatingFileHandler 备份旧的日志文件并使用RotatingFileHandler创建新文件

  2. Replace the file itself (provided you don't need the old log anymore). 替换文件本身(前提是您不再需要旧的日志)。 You can have a look at this for the steps 您可以查看步骤

Hope this helps. 希望这可以帮助。

Instead of using the logger module, would you be able to use the below instead? 除了使用记录器模块之外,您还可以使用以下模块吗?

open("result_log.txt", "w").write("result")

I understand this would be a workaround for now, until someone is able to answer this question better. 我知道这是暂时的解决方法,直到有人能够更好地回答这个问题。

Hope this helps :) 希望这可以帮助 :)

In fact, you can set filemode to w from within your configuration file. 实际上,您可以从配置文件中将filemode设置为w You just need to remove the explicit argument naming, like so: 您只需要删除显式参数命名,如下所示:

args=('result_log.txt','w')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM