使用Python断言记录的“规范”方法

时间:2016-02-16 20:31:54

标签: python logging

在以下代码中,#include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { int size; int i; printf("Choose size of array: "); scanf("%d",&size); /*---MALLOC/FREE---*/ int *m_array = (int *)malloc((size+1)*sizeof(int)); memset(m_array,'\0',size+1); for(i=0; i<size ; i++) { m_array[i]=i; printf("%d ",m_array[i]); } printf("\n"); free(m_array); return 0; } 在单元测试之外使用:

assert

打印如下:

import logging

if __name__ == "__main__":
    logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO)
    logger = logging.getLogger(__name__)
    logger.info("info level")
    assert 1 == 0

使用2016-02-16 14:56:58,445 - __main__ - INFO - info level Traceback (most recent call last): File "logtest.py", line 7, in <module> assert 1 == 0 AssertionError 引发的AssertionError的带时间戳记录格式的“规范”方法是什么(可能没有重写代码中的每个assert)?

提出了许多类似的问题,主要是在单元测试环境中处理assert ... 感谢

1 个答案:

答案 0 :(得分:3)

当您处理记录异常时,您的代码可能会在try except中出错,然后记录异常,例如:

try:
    assert 1 == 0 
except AssertionError as err:
    logger.exception("My assert failed :( ")
    raise err

然后它会记录:

2016-02-16 15:29:43,009 - __main__ - INFO - info level
2016-02-16 15:29:43,009 - __main__ - ERROR - My assert failed :( 
Traceback (most recent call last):
  File "/home/james/PycharmProjects/scratchyard/test_time.py", line 8, in <module>
    assert 1 == 0
AssertionError