python中的日志记录模块;有没有办法记录所有减少调试?

时间:2017-04-24 14:34:45

标签: python logging

有没有办法记录所有减少调试? 我希望在文件中写入信息,警告,关键和错误,以及其他任何内容。

这是因为记录调试也很难搜索。

在这一刻我正在做:

import logging
logging.basicConfig(filename='loggs.log', format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p',level=logging.DEBUG)
logging.info('Start Test API.')

通过这种方式我记录了一切,但我想限制它!

在阅读了一些文档后,我正在这样做:

LEVELS = {'info': logging.INFO,
          'warning': logging.WARNING,
          'error': logging.ERROR,
          'critical': logging.CRITICAL}

#define the loggs configuration
if len(sys.argv) > 1:
    level_name = sys.argv[1]
    level = LEVELS.get(level_name, logging.NOTSET)
    logging.basicConfig(filename='loggs.log', format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p',level=level)
logging.info('Start Test API.')

所以我期待日志'开始测试API。',而不是我的文件是空的!

2 个答案:

答案 0 :(得分:3)

而不是:

logging.basicConfig(filename='loggs.log', format='', datefmt='', level=logging.DEBUG)

你想:

logging.basicConfig(filename='loggs.log', format='', datefmt='', level=logging.INFO)

请参阅官方文档:https://docs.python.org/3.5/library/logging.html

示例:

import logging
import sys

LEVELS = {'debug': logging.DEBUG,
          'info': logging.INFO,
          'warning': logging.WARNING,
          'error': logging.ERROR,
          'critical': logging.CRITICAL}

if len(sys.argv) > 1:
    level_name = sys.argv[1]
    level = LEVELS.get(level_name, logging.NOTSET)
    logging.basicConfig(level=level)

logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical error message')

产地:

$ python logging_level_example.py debug
DEBUG:root:This is a debug message
INFO:root:This is an info message
WARNING:root:This is a warning message
ERROR:root:This is an error message
CRITICAL:root:This is a critical error message

$ python logging_level_example.py info
INFO:root:This is an info message
WARNING:root:This is a warning message
ERROR:root:This is an error message
CRITICAL:root:This is a critical error message

答案 1 :(得分:0)

您可以使用setLevel方法将级别设置为限制日志记录。

相关问题