简体   繁体   English

python:将输出从外部API记录到记录器模块

[英]python: logging output from external API to logger module

I am python beginner. 我是python初学者。 My python script logs output to a file (say example.log) using the basic python logging module. 我的python脚本使用基本的python日志记录模块将输出记录到文件(例如example.log)中。 However, my python script also makes some 3rd party API calls (for example, parse_the_file) over which I don't have any control. 但是,我的python脚本还进行了一些我无法控制的第三方API调用(例如parse_the_file)。 I want to capture the output (usually on console) produced by the API into my example.log. 我想将API产生的输出(通常在控制台上)捕获到example.log中。 The following example code works partially but the problem is that the contents get overwritten as soon as I start logging output of the API into my log file. 以下示例代码部分起作用,但是问题是,一旦我开始将API输出记录到日志文件中,内容就会被覆盖。

#!/usr/bin/env python

import logging
import sys
import os
from common_lib import *     # import additional modules

logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')

logging.debug('This is a log message.') # message goes to log file.

sys.stdout = open('example.log','a')
metadata_func=parse_the_file('/opt/metadata.txt') # output goes to log file but OVERWRITES the content
sys.stdout = sys.__stdout__
logging.debug('This is a second log message.') # message goes to log file.

I know there have been post suggesting to similar question on this site but I haven't a workaround/solution for this problem that will work in this scenario. 我知道这个网站上有过类似问题的建议,但我没有针对该问题的解决方法/解决方案,在这种情况下将无法解决。

Try: 尝试:

log_file = open('example.log', 'a')
logging.basicConfig(stream=log_file, level=logging.DEBUG)
logging.debug("Test")
sys.stdout = log_file
sys.stderr = log_file
stdout_fd = os.dup(1)
stderr_fd = os.dup(2)
os.dup2(log_file.fileno(), 1)
os.dup2(log_file.fileno(), 2)

os.system("echo foo")

os.dup2(stdout_fd, 1)
os.dup2(stderr_fd, 2)
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__

However, this will not format it accordingly. 但是,这不会相应地格式化它。 If you want that, you can try something like http://plumberjack.blogspot.com/2009/09/how-to-treat-logger-like-output-stream.html 如果需要,您可以尝试使用类似http://plumberjack.blogspot.com/2009/09/how-to-treat-logger-like-output-stream.html的方法

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

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