我正在创建一个自定义日志记录模块,以便在应用程序框架中实现。我正在使用PyCharm,unittest
模块和nosetests作为我的测试运行员。
这是一个简单的测试用例,但它没有像我希望的那样将输出保存到文件/tmp/test.log
。
import unittest
import logging
class Logger_class____test_cases(unittest.TestCase):
def test_log_file_basics(self):
# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG,
filename='/tmp/test.log')
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
# Now, we can log to the root logger, or any other logger. First the root...
logging.info('Jackdaws love my big sphinx of quartz.')
# Now, define a couple of other loggers which might represent areas in your
# application:
logger1 = logging.getLogger('myapp.area1')
logger2 = logging.getLogger('myapp.area2')
logger1.debug('Quick zephyrs blow, vexing daft Jim.')
logger1.info('How quickly daft jumping zebras vex.')
logger2.warning('Jail zesty vixen who grabbed pay from quack.')
logger2.error('The five boxing wizards jump quickly.')
如何通过nosetests将日志输出写入文件?它似乎与捕获stdout
和stderr
的测试有关,但我似乎无法弄明白。
我从Python logging cookbook获得了代码。
答案 0 :(得分:0)
我明白了。我在框架中的全局模块中配置了默认日志文件名。
我有类似以下的内容覆盖了我的测试用例:
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
filename='log_file_name.log',
filemode='w')
当然墨菲定律,如果我发一个问题,我会很快找到答案。洛尔