将stdout从多个进程重定向到python Logging模块

时间:2010-11-30 16:38:49

标签: python redirect subprocess stdout popen

我有一个python脚本,它使用subprocess.Popen启动了许多用户进程。每个进程stdout都被重定向到一个唯一的文件。例如,我按如下方式启动每个流程

proc = my_proc  
for p in range(1, max_p, 1):  
    log_file = proc + "_" + str(p) + ".log"  
    log = open(log_file, "w+")  
    subprocess.Popen([my_proc, p], shell = False, stdout = log)  

我想在这些文件太大时旋转这些文件。这样做的最佳方法是什么?我想使用日志模块,但我不认为这是它的预期用途

由于

2 个答案:

答案 0 :(得分:1)

不是pythonic解决方案;但在Linux系统上,我更喜欢使用logrotate自动旋转我的日志。检查它是否安装在你的系统上(在ubuntu上说有一个名为/etc/logrotate.d/的目录,文件自动通过cron运行)。这可能是也可能不是从应用程序中运行日志轮换的首选。

它是非常可配置的,例如,允许压缩旧文件通过旋转N命令保持N个文件,当cron超过“大小100k”时旋转,并且看着man logrotate,它非常简单地设置。

从手册页这里是一个示例文件

   # sample logrotate configuration file
   compress

   /var/log/messages {
       rotate 5
       weekly
       postrotate
           /usr/bin/killall -HUP syslogd
       endscript
   }

   "/var/log/httpd/access.log" /var/log/httpd/error.log {
       rotate 5
       mail www@my.org
       size 100k
       sharedscripts
       postrotate
           /usr/bin/killall -HUP httpd
       endscript
   }

答案 1 :(得分:0)

logging.handlers.RotatingFileHandler怎么样?

相关问题