我编写了一个程序并使用日志工具(例如,Java的log4j或Python的logging)处理日志,这样由我自己生成的所有日志都可以转到日志工具管理的日志文件中。
我还会在程序中调用一个命令或第三方程序,默认情况下,该命令或第三方程序会将其所有输出写入控制台。如何将这些输出重定向到日志工具管理的日志文件(如果可能的话,使它们符合日志记录格式)?
发布于 2015-09-01 09:48:42
若要将外部进程的所有标准输出重定向到Python中的文件:
#!/usr/bin/env python
from subprocess import check_call, STDOUT
with open('log', 'ab', 0) as file:
check_call(['program', 'arg 1', 'arg 2'], stdout=file, stderr=STDOUT)输出按原样重定向。为了使其符合日志记录格式,您可能需要它显式地通过您的程序:
#!/usr/bin/env python3
import logging
from subprocess import Popen, PIPE, STDOUT
logging.basicConfig(filename='log',level=logging.DEBUG)
with Popen(['program', 'arg 1', 'arg 2'], stdout=PIPE, stderr=STDOUT, bufsize=1,
universal_newlines=True) as process:
for line in process.stdout:
logging.debug('program output %s', line.rstrip('\n'))代码使用locale.getpreferredencoding(False)解码程序的标准输出,并使用logging模块将行附加到日志文件中(您可以使用标准的logging工具配置任何日志格式)。
发布于 2015-09-01 07:58:04
在java中,您可以使用来自log4j的log4j来构建PrintStream。IoBuilder包含在Apache的Log4J流接口中,这是对Log4j的一个补充。
一旦您拥有了PrintStream,就可以设置系统的默认PrintStream.
IoBuilder builder = IoBuilder.forLogger(MyClass.class);
PrintStream myPrintStream = builder.buildPrintStream();
System.out = myPrintStream;这样,如果其他库转到System.out.print()或println(),它将以记录器格式通过您的记录器进行记录。
https://stackoverflow.com/questions/32326077
复制相似问题