【问题标题】:how to get Python logging messages to appear for modules using custom handler如何使用自定义处理程序为模块显示 Python 日志记录消息
【发布时间】:2014-12-15 01:06:26
【问题描述】:

我正在尝试使用/编写自定义 Python 日志记录处理程序。当我使用它时,日志会出现在我的主代码中,但不会出现在它使用的模块中。我只是不知道如何让模块mylib 的日志记录出现并欢迎帮助。我确定我在处理处理程序时只是做一些简单的错误。

程序的主要代码如下(main.py):

import logging
import colorlogging
import mylib

def main():
    global log
    log = logging.getLogger(__name__)
    log.addHandler(colorlogging.ColorisingStreamHandler())
    log.setLevel(logging.DEBUG)

    log.info('started main program')
    mylib.do_something()
    log.debug('main program debug message')
    log.info('finished main program')

if __name__ == '__main__':
    main()

程序使用的模块如下(mylib.py):

import logging

log = logging.getLogger(__name__)

def do_something():
    log.info('doing something')
    log.debug('library debug message')

处理程序代码如下(colorlogging.py):

import ctypes
import logging
import os

class ColorisingStreamHandler(logging.StreamHandler):

    # color names to indices
    colorMap = {
        'black':   0,
        'red':     1,
        'green':   2,
        'yellow':  3,
        'blue':    4,
        'magenta': 5,
        'cyan':    6,
        'white':   7,
    }

    # level colour specifications
    # syntax: logging.level: (background color, foreground color, bold)
    levelMap = {
        logging.DEBUG:    (None,   'blue',    False),
        logging.INFO:     (None,   'white',   False),
        logging.WARNING:  (None,   'yellow',  False),
        logging.ERROR:    (None,   'red',     False),
        logging.CRITICAL: ('red',  'white',   True),
    }

    # control sequence introducer
    CSI = '\x1b['

    # normal colours
    reset = '\x1b[0m'

    def istty(self):
        isatty = getattr(self.stream, 'isatty', None)
        return isatty and isatty()

    def emit(self, record):
        try:
            message = self.format(record)
            stream = self.stream
            if not self.istty:
                stream.write(message)
            else:
                self.outputColorised(message)
            stream.write(getattr(self, 'terminator', '\n'))
            self.flush()
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)

    def outputColorised(self, message):
        self.stream.write(message)

    def colorise(self, message, record):
        if record.levelno in self.levelMap:
            backgroundColor, \
            foregroundColor, \
            bold = self.levelMap[record.levelno]
            parameters = []
            if backgroundColor in self.colorMap:
                parameters.append(str(self.colorMap[backgroundColor] + 40))
            if foregroundColor in self.colorMap:
                parameters.append(str(self.colorMap[foregroundColor] + 30))
            if bold:
                parameters.append('1')
            if parameters:
                message = ''.join((
                    self.CSI,
                    ';'.join(parameters),
                    'm',
                    message,
                    self.reset
                ))
        return message

    def format(self, record):
        message = logging.StreamHandler.format(self, record)
        if self.istty:
            # Do not colorise traceback.
            parts = message.split('\n', 1)
            parts[0] = self.colorise(parts[0], record)
            message = '\n'.join(parts)
        return message

【问题讨论】:

    标签: python logging module handler


    【解决方案1】:

    ColorisingStreamHandler 添加到根记录器,以便will affect all child loggers 传播记录。

    ma​​in.py:

    import logging
    import colorlogging
    import mylib
    
    def main():
        global log
        log = logging.getLogger(__name__)
        root = logging.root
        root.addHandler(colorlogging.ColorisingStreamHandler())
        root.setLevel(logging.DEBUG)
    
        log.info('started main program')
        mylib.do_something()
        log.debug('main program debug message')
        log.info('finished main program')
    
    if __name__ == '__main__':
        main()
    

    产量

    started main program             (white)
    doing something                  (white)
    library debug message            (blue)
    main program debug message       (blue)
    finished main program            (white)
    

    【讨论】:

    • 非常感谢您的帮助!我想我看到您仅将处理程序添加到“最顶层”记录器。快速提问:是否有一种明智的方法可以只设置一次日志记录级别?在我的非最小主程序中,我实际上是使用命令行详细控制设置日志记录级别。以下看起来合理吗? logging.root.setLevel(logging.DEBUG)
    • 确实,您可以设置根日志记录级别。
    猜你喜欢
    • 2011-03-08
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    相关资源
    最近更新 更多