首页 > 解决方案 > 为什么调试级别不适用于此配置?

问题描述

我注意到在启动我的主脚本时使用 DEBUG 级别进行日志记录期间没有写入任何内容:python -m src.scripts,所以我使用了 ipdb,如下所示:

import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

file_handler = logging.FileHandler(os.path.join('logs','pdfparser.log'))
formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(name)s:%(message)s')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

def pix2np(pix):
    """
    Convert pixmap to image
    https://stackoverflow.com/questions/53059007/python-opencv
    """
    import numpy as np
    im = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.h, pix.w, pix.n)
    try:
        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # rgb to bgr
    except IndexError:
        #Trick to convert Gray rto BGR,
        logger.debug("Shape of image array is {}".format(im.shape)) 
        import ipdb;ipdb.set_trace()
        im = cv2.cvtColor(im,cv2.COLOR_GRAY2RGB)
        im = np.ascontiguousarray(im[..., [2, 1, 0]])
    return im

我手动输入了以下命令

我刚刚得到以下结果(在 pdfparser.log 中):

ipdb> logger.info('test')
ipdb> logger.warning('test2')
ipdb> logger.debug('test2')
ipdb> logger.error('test2')
ipdb> logger.debug('test3')
ipdb> logger.error('test3')
ipdb> logger.exception('test3')
2020-10-22 11:13:51,498INFO:impocr.pdfparser:test
2020-10-22 11:14:10,004WARNING:impocr.pdfparser:test2
2020-10-22 11:14:49,745ERROR:impocr.pdfparser:test2
2020-10-22 11:15:13,497ERROR:impocr.pdfparser:test3
2020-10-22 11:16:35,722ERROR:impocr.pdfparser:test3
Traceback (most recent call last):
  File "C:\Users\pincemaille\OneDrive - Groupe BPCE\Python\Impots\impocr\pdfparser.py", line 26, in pix2np
    im = np.ascontiguousarray(im[..., [2, 1, 0]])  # rgb to bgr
IndexError: index 2 is out of bounds for axis 2 with size 1

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files\Python38\lib\cmd.py", line 214, in onecmd
    func = getattr(self, 'do_' + cmd)
AttributeError: 'TerminalPdb' object has no attribute 'do_logger'

真正奇怪的是 logging.info 工作但不是调试级别。

标签: pythonpython-3.xlogging

解决方案


您已将记录器级别设置为INFO

logger.setLevel(logging.INFO)

这意味着您以低于 的级别记录的任何内容都INFO将被忽略。DEBUG低于INFO

https://docs.python.org/3/library/logging.html#logging-levels

如果您希望在日志中包含调试消息,请将记录器级别设置为logging.DEBUG


推荐阅读