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

标签 python logging python-2.7 operating-system

我正在使用以下代码来记录

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中正确处理记录器文件大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19107973/

相关文章:

python - OpenCV-平滑边框

javascript - Sails.js 日志传输取决于环境

java - 跟踪代码管理器不再工作 - Android Studio 2.2.2

python - 在 Beautifulsoup 中使用 select 函数返回 None 值

php - 什么是 strpos($elem ,"text") !== false) 的 python 等价物

python - 如何在 Flask/Jinja 中选择/减少字典列表

python - 高效标准化 Numpy 数组中的图像

python - 如何统计提交的 GET 参数的数量?

java - 缓冲记录器 (Java)

python-2.7 - Elasticsearch 5.4-按术语过滤是否存在术语,不存在则不过滤