我正在使用以下代码来记录
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
。这需要 maxBytes
和 backupCount
关键字参数。来自文档:
You can use the
maxBytes
andbackupCount
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 nearlymaxBytes
in length; ifmaxBytes
is zero, rollover never occurs. IfbackupCount
is non-zero, the system will save old log files by appending the extensions ‘.1’, ‘.2’ etc., to the filename. For example, with abackupCount
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中正确处理记录器文件大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19107973/