解决这个问题最直接的方法可能是使用 python 和为此目的设计的日志记录模块。创建一个脚本来读取stdin
和写入stdout
并实现下面描述的日志轮换。
“日志”模块提供
class logging.handlers.RotatingFileHandler(filename, mode='a', maxBytes=0,
backupCount=0, encoding=None, delay=0)
这正是您要问的。
您可以使用 maxBytes 和 backupCount 值来允许文件以预定大小翻转。
来自docs.python.org
有时您想让日志文件增长到一定大小,然后打开一个新文件并记录到该文件。您可能希望保留一定数量的这些文件,并在创建了这么多文件后,旋转文件以使文件数量和文件大小都保持有限。对于这种使用模式,日志包提供了一个 RotatingFileHandler:
import glob
import logging
import logging.handlers
LOG_FILENAME = 'logging_rotatingfile_example.out'
# Set up a specific logger with our desired output level
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(
LOG_FILENAME, maxBytes=20, backupCount=5)
my_logger.addHandler(handler)
# Log some messages
for i in range(20):
my_logger.debug('i = %d' % i)
# See what files are created
logfiles = glob.glob('%s*' % LOG_FILENAME)
for filename in logfiles:
print(filename)
结果应该是 6 个单独的文件,每个文件都包含应用程序的部分日志历史记录:
logging_rotatingfile_example.out
logging_rotatingfile_example.out.1
logging_rotatingfile_example.out.2
logging_rotatingfile_example.out.3
logging_rotatingfile_example.out.4
logging_rotatingfile_example.out.5
最新的文件始终是 logging_rotatingfile_example.out,每次达到大小限制时,都会使用后缀 .1 重命名。每个现有备份文件都被重命名以增加后缀(.1 变为 .2,等等),并且 .6 文件被删除。
显然,作为一个极端示例,此示例将日志长度设置得太小。您可能希望将 maxBytes 设置为适当的值。