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

时间:2011-05-19 05:02:24

标签: python automation logging

我正在尝试创建一个testcontroller,并希望将测试的执行收集到一个文件中。

我知道使用,tee并将测试脚本执行重定向到某个文件,但我有兴趣用python over linux。

因此,在这种情况下,无论何时执行测试,都应该创建日志文件,并且应该收集包括stdin,stdout和stderr在内的所有执行日志。

请求某个机构建议我,如何实现这种想法!

由于 的OpenFile

5 个答案:

答案 0 :(得分:5)

有几个好的日志记录模块,从内置logging开始,这里是official cookbook。在更有趣的第三方库中有Logbook,这是一个非常简单的例子,只是抓住了very cool features的表面:

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

答案 1 :(得分: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()

答案 2 :(得分:2)

打开并写入文件:

mylogfile = 'bla.log'
f = open(mylogfile, 'a')
f.write('i am logging! logging logging!....loggin? timber!....')
f.close()

在'bla.log'的脚本的根目录中查看并阅读,享受

答案 3 :(得分:2)

您可以编写如下函数:

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

它将打开文件“ log ”,并附加(“ a ”)消息后跟换行符,然后关闭文件。

答案 4 :(得分:0)

# Save the current stream
saveout = sys.stdout


f = "a_log_file.log"
fsock = open(f, 'w')

# Set stream to file
sys.stdout = fsock

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

# Reset back the stream to what it was
sys.stdout = saveout
fsock.close()