简体   繁体   English

如何使用日志记录模块将Python的unittest模块错误回溯重定向到日志文件?

[英]How to redirect Python's unittest modules error traceback to log file using logging module?

I have a python test script and I am trying to redirect its output(stdout and stderr) both to console and a log file.The script produces following output in console which is what I want. 我有一个python测试脚本,我试图将其输出(stdout和stderr)都重定向到控制台和日志文件。该脚本在控制台中生成我想要的以下输出。

test_valid_timerange (testapp.TestApp) ... FAIL
test_has_dashboard_description (testapp.TestApp) ... ok

======================================================================
FAIL: test_valid_timerange (testapp.TestApp)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/himanshu/git/content/test/testapp.py", line 135, in test_valid_timerange
    "%s: panel %s in dashboard %s does not use relative url" % (self.appname, dash.get("name"), panel.get("name")))
AssertionError: Kubernetes: panel Kubernetes - Kube-System in dashboard Pod and Container Running in Kube-System does not use relative url

----------------------------------------------------------------------
Ran 2 tests in 0.001s

FAILED (failures=1)

But in log file I am getting only this. 但是在日志文件中,我只能得到这个。

2018-06-29 18:29:56,289 [MainThread  ] [INFO ]  Starting Tests for manifestfile: /Users/himanshu/git/content/src/main/app-package/kubernetes/kops/kubernetes.manifest.json appfile: /Users/himanshu/git/content/src/main/app-package/kubernetes/kops/kubernetes.json
2018-06-29 18:29:56,341 [MainThread  ] [INFO ]  testing Kubernetes: test_valid_timerange
2018-06-29 18:29:56,341 [MainThread  ] [INFO ]  testing Kubernetes: test_has_dashboard_description
2018-06-29 18:29:56,342 [MainThread  ] [DEBUG]  Results - Total TestCases: 2 Total Failed: 1

I know one way of doing it is to explicitly get failures and errors from result object of test and printing them using a logger whose handler outputs only to file(This is because if I use my current logger it has both streamhandler and filehandler and it will print failure messages two times in console). 我知道这样做的一种方法是从测试结果对象中明确获取失败和错误,并使用记录程序将其打印出来,记录程序的处理程序仅输出到文件(这是因为如果使用当前的记录程序,它既具有流处理程序又具有文件处理程序,并且它将在控制台中两次打印失败消息)。 This is my current code 这是我当前的代码

def get_logger():
    log = logging.getLogger(__name__)
    if not log.handlers:

        log.setLevel(logging.DEBUG)
        logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s")

        consoleHandler = logging.StreamHandler(sys.stdout)
        consoleHandler.setFormatter(logFormatter)
        log.addHandler(consoleHandler)

        filehandler = RotatingFileHandler(LOGFILE, maxBytes=(1024*1024*25), backupCount=7)
        filehandler.setFormatter(logFormatter)
        log.addHandler(filehandler)

    return log

logger = get_logger()
suite = unittest.TestSuite()
// using suite.addTest to add tests and using logger in each test function
result = unittest.TextTestRunner().run(suite)

Is there any other better way possible without creating another logger with a single handler? 如果不使用单个处理程序创建另一个记录器,还有其他更好的方法吗? I am looking for alternatives like passing a logger while create test suite (unittest.TestSuite(logger=mylogger)) or using the same logger but explicitly passing an argument to use a specific handler(logger.info(msg, using=filehandler)) or pass some argument which stops printing failure msg to console and i can use my custom logger to print to both console and file. 我正在寻找替代方案,例如在创建测试套件时传递记录器(unittest.TestSuite(logger = mylogger))或使用相同的记录器,但显式传递参数以使用特定的处理程序(logger.info(msg,using = filehandler))或通过传递一些参数来停止向控制台输出失败的消息,我可以使用我的自定义记录器同时打印到控制台和文件。

I used something similar to as mentioned here 我使用了类似于此处提到的内容

class LoggerWriter:
    def __init__(self, logger):
        self.logger = logger

    def write(self, message):
        if message != '\n' and message != " ... ":
            self.logger.debug(message)

    def flush(self):
        pass

suite = unittest.TestSuite()
result = unittest.TextTestRunner(stream=LoggerWriter(logger), verbosity=3).run(suite)

PS I still don't know whether it's the best way to solve the problem. PS我仍然不知道这是否是解决问题的最佳方法。

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

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