gpt4 book ai didi

python - 如何在 Python 中正确处理 Logger 文件大小?

转载 作者:太空宇宙 更新时间:2023-11-04 03:55:00 25 4
gpt4 key购买 nike

我正在使用下面的代码来记录

logging.basicConfig(filename=os.environ['USERPROFILE']+'\\myApp', level=logging.DEBUG, format='%(asctime)s - [Thread-%(thread)d] - [Process-%(process)d] - %(levelname)s - %(funcName)s - %(lineno)d - %(message)s')

有了这个日志记录,我们可以实现记录器文件的文件大小限制,比如如果日志文件大小超过 5MB,那么我想将它写入新文件。

在 Java 中,我们可以在 logback.xml 中指定文件大小,如下所示

 <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>10MB</maxFileSize>
</triggeringPolicy>

最佳答案

使用 RotatingFileHandler .这需要 maxBytesbackupCount 关键字参数。来自文档:

You can use the maxBytes and backupCount values to allow the file to rollover at a predetermined size. When the size is about to be exceeded, the file is closed and a new file is silently opened for output. Rollover occurs whenever the current log file is nearly maxBytes in length; if maxBytes is zero, rollover never occurs. If backupCount is non-zero, the system will save old log files by appending the extensions ‘.1’, ‘.2’ etc., to the filename. For example, with a backupCount of 5 and a base file name of app.log, you would get app.log, app.log.1, app.log.2, up to app.log.5. The file being written to is always app.log. When this file is filled, it is closed and renamed to app.log.1, and if files app.log.1, app.log.2, etc. exist, then they are renamed to app.log.2, app.log.3 etc. respectively.

关于python - 如何在 Python 中正确处理 Logger 文件大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19107973/

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