繁体   English   中英

如何使用自定义处理程序使Python日志记录消息出现在模块中

[英]how to get Python logging messages to appear for modules using custom handler

我正在尝试使用/编写自定义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

ColorisingStreamHandler添加到根记录器,这样它将影响传播记录的所有子记录器

main.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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM