如何为测试执行创建日志文件

1 投票
5 回答
10732 浏览
提问于 2025-04-16 17:56

我想创建一个测试控制器,并希望将测试执行的结果收集到一个文件里。

我知道可以使用tee命令和重定向来把测试脚本的执行结果保存到某个文件,但我想用Python在Linux上实现这个功能。

所以,在这种情况下,每当执行一个测试时,应该创建一个日志文件,并把所有的执行日志,包括标准输入、标准输出和标准错误,都收集到这个文件里。

希望有人能给我建议,怎么实现这个想法!

谢谢,OpenFile

5 个回答

2

你可以写一个这样的函数:

def writeInLog(msg):
    with open("log", "a") as f:
        f.write(msg+"\n")

这个函数会打开一个名为 "log" 的文件,然后在文件末尾添加一条信息,并在信息后面加一个换行符,最后再关闭这个文件。

3

试试这个:

import sys

# Save the current stream
save_out = sys.stdout

# Define the log file
f = "a_log_file.log"
# Append to existing log file. 
# Change 'a' to 'w' to recreate the log file each time.
fsock = open(f, 'a')

# Set stream to file
sys.stdout = fsock

###
# do something here 
# any print function calls will send the stream to file f
###

# Reset back the stream to what it was
# any print function calls will send the stream to the previous stream
sys.stdout = save_out
fsock.close()
5

有几个不错的日志记录模块,首先是内置的 logging 模块,这里有一个 官方的使用手册。在一些有趣的第三方库中,有一个叫 Logbook 的库,这里有一个非常简单的例子,刚刚触及到它的一些 很酷的功能

import logbook

def f(i,j):
    return i+j

logger = logbook.Logger('my application logger')
log = logbook.FileHandler('so.log')
log.push_application()

try:
    f(1, '2')
    logger.info('called '+f.__name__)
except:
    logger.warn('failed on ')


try:
    f(1, 2)
    logger.info('called '+f.__name__)
except:
    logger.warn('choked on, ')

so.log 看起来是这样的:

[2011-05-19 07:40] WARNING: my application logger: failed on
[2011-05-19 07:40] INFO: my application logger: called f

撰写回答