简体   繁体   English

如何将调用的命令/程序的输出重定向到log4j?

[英]How to redirect outputs of invoked commands/programs to log4j?

I write a program and handle my logs with a logging tool (eg, Java's log4j or Python's logging ), so all logs produced by myself can go to a log file managed by the logging tool. 我编写了程序并使用日志记录工具(例如Java的log4j或Python的logging )处理logging ,因此,我自己生成的所有日志都可以转到由日志记录工具管理的日志文件中。

I'd also invoke a command or a third party program in my program, which writes all its outputs to the console by default. 我还将在程序中调用命令或第三方程序,默认情况下,它将所有输出写入控制台。 How can I redirect those outputs to the log file managed by the logging tool (and make them conform to the logging format if possible)? 如何将这些输出重定向到由日志记录工具管理的日志文件(并在可能的情况下使其符合日志记录格式)?

In java, you could use IoBuilder from log4j to build your PrintStream. 在Java中,您可以使用log4j中的IoBuilder来构建PrintStream。 IoBuilder is included in Apache's Log4j Streaming Interface, an addition to Log4J. IoBuilder包含在Apache的Log4j流接口中,它是Log4J的补充。

Once you have your PrintStream, you can set the system's default PrintStream... 拥有PrintStream之后,您可以设置系统的默认PrintStream ...

 IoBuilder builder = IoBuilder.forLogger(MyClass.class);
 PrintStream myPrintStream = builder.buildPrintStream();
 System.out = myPrintStream;

This way, if other library goes System.out.print() or println() it will be logged through your logger, with your logger format. 这样,如果其他库进入System.out.print()println() ,它将通过您的记录器以记录器格式进行记录。

To redirect all standard output of an external process to a file in Python: 要将外部进程的所有标准输出重定向到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)

The output is redirected as is. 输出将按原样重定向。 To make it conform to the logging format, you might need it to pass through your program explicitly: 为了使其符合日志记录格式,您可能需要它明确地通过程序:

#!/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'))

The code decodes program's standard output using locale.getpreferredencoding(False) and appends lines to the log file using logging module (you could configure whatever logging format you like using standard logging tools). 该代码使用locale.getpreferredencoding(False)解码程序的标准输出,并使用logging模块将行追加到日志文件中(您可以使用标准logging工具配置所需的任何日志记录格式)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM