这个问题最直接的解决方法可能是使用Python和专为此目的设计的
日志记录模块。创建一个从
stdin
读取并写入
stdout
的脚本,并实现下面描述的日志轮换。
"logging"模块
提供了
class logging.handlers.RotatingFileHandler(filename, mode='a', maxBytes=0,
backupCount=0, encoding=None, delay=0)
这段文字的意思是:“它正好可以做到你所要求的那样。你可以使用maxBytes和backupCount值来允许文件在预定大小时翻转。此外,当创建了一定数量的文件后,你可能希望将文件进行轮换,以便保持文件数目和文件大小都有限制。对于这种用法模式,logging包提供了RotatingFileHandler。”出处为“
docs.python.org”。
import glob
import logging
import logging.handlers
LOG_FILENAME = 'logging_rotatingfile_example.out'
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
handler = logging.handlers.RotatingFileHandler(
LOG_FILENAME, maxBytes=20, backupCount=5)
my_logger.addHandler(handler)
for i in range(20):
my_logger.debug('i = %d' % i)
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设置为适当的值。
tee
的第一种解决方案,我为什么不应该使用my_program | tee | split -d -b 100000 -
? - asafctee >(split --additional-suffix=.log -d -b 1000000 - debug.0)
。 - rubo77tee
读取stdin
并写入两个副本,一个写入文件,另一个写入tee
的stdout
。需要拆分/旋转的是文件输出。您的建议将消耗用于在终端上显示的stdout
副本,从而破坏使用tee
的整个原因。 - Ben Voigt