【发布时间】:2018-12-08 16:42:37
【问题描述】:
我有一个 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)
但在日志文件中我只得到这个。
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
我知道这样做的一种方法是从测试的结果对象中显式获取失败和错误,并使用其处理程序仅输出到文件的记录器打印它们(这是因为如果我使用当前的记录器,它同时具有流处理程序和文件处理程序它将在控制台中打印两次失败消息)。这是我当前的代码
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)
如果不使用单个处理程序创建另一个记录器,还有其他更好的方法吗?我正在寻找替代方法,例如在创建测试套件时传递记录器 (unittest.TestSuite(logger=mylogger)) 或使用相同的记录器但显式传递参数以使用特定的处理程序(logger.info(msg, using=filehandler))或将一些停止打印失败消息的参数传递给控制台,我可以使用我的自定义记录器打印到控制台和文件。
【问题讨论】:
标签: python python-2.7 logging python-unittest