扩展Python日志

2024-04-19 16:36:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种简单的方法来扩展标准python库中定义的logging功能。我只想能够选择我的日志是否也打印到屏幕上。

示例:通常要记录您将调用的警告:

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s: %(message)s', filename='log.log', filemode='w')
logging.warning("WARNING!!!")

这将设置日志的配置并将警告放入日志中

我想要一个类似电话的东西:

logging.warning("WARNING!!!", True)

其中,True语句表示日志是否也打印到stdout。

我看过一些实现overriding the logger class的例子

但我对这门语言还不太了解,也不知道如何实现这个想法。任何帮助都将不胜感激:)


Tags: 方法功能logtrue警告示例标准定义
3条回答

Handlers send the log records (created by loggers) to the appropriate destination.

(来自文档:http://docs.python.org/library/logging.html

只需使用日志对象设置多个处理程序,一个用于写入文件,另一个用于写入屏幕。

更新

下面是一个示例函数,您可以在类中调用该函数以使用处理程序设置日志记录。

def set_up_logger(self):
    # create logger object
    self.log = logging.getLogger("command")
    self.log.setLevel(logging.DEBUG)

    # create console handler and set min level recorded to debug messages
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)

    # add the handler to the log object        
    self.log.addHandler(ch)

您只需要为文件设置另一个处理程序,即已经存在的StreamHandler代码,并将其添加到日志对象中。表示ch.setLevel(logging.DEBUG)的行意味着此特定处理程序将接收调试或更高版本的日志消息。您可能希望将您的设置为警告或更高,因为您只希望将更重要的事情转到控制台。所以,日志记录的工作方式如下:

self.log.info("Hello, World!") -> goes to file
self.log.error("OMG!!") -> goes to file AND console

可以重写logging.getLoggerClass()以向记录器添加新功能。我写了一个简单的类,它在stdout中打印绿色消息。

我的代码中最重要的部分:

class ColorLogger(logging.getLoggerClass()):
    __GREEN = '\033[0;32m%s\033[0m'
    __FORMAT = {
        'fmt': '%(asctime)s %(levelname)s: %(message)s',
        'datefmt': '%Y-%m-%d %H:%M:%S',
    }

    def __init__(self, format=__FORMAT):
        formatter = logging.Formatter(**format)

        self.root.setLevel(logging.INFO)
        self.root.handlers = []

        (...)

        handler = logging.StreamHandler()
        handler.setFormatter(formatter)
        self.root.addHandler(handler)

    def info(self, message):
        self.root.info(message)

    (...)

    def info_green(self, message):
        self.root.info(self.__GREEN, message)

(...)

if __name__ == '__main__':
    logger = ColorLogger()
    logger.info("This message has default color.")
    logger.info_green("This message is green.")

Python日志模块定义了以下类:

发出日志消息的记录器。
将这些消息放到目的地的处理程序。
格式化程序格式化日志消息。
过滤日志消息。

记录器可以有处理程序。通过调用addHandler()方法添加它们。处理程序可以有过滤器和格式化程序。类似地,通过分别调用addFilter()setFormatter()方法添加它们。

它的工作原理如下:

import logging

# make a logger
main_logger = logging.getLogger("my logger")
main_logger.setLevel(logging.INFO)

# make some handlers
console_handler = logging.StreamHandler() # by default, sys.stderr
file_handler    = logging.FileHandler("my_log_file.txt")

# set logging levels
console_handler.setLevel(logging.WARNING)
file_handler.setLevel(logging.INFO)

# add handlers to logger
main_logger.addHandler(console_handler)
main_logger.addHandler(file_handler)

现在,可以这样使用此对象:

main_logger.info("logged in the FILE")
main_logger.warning("logged in the FILE and on the CONSOLE")

如果你只是在你的机器上运行python,你可以在交互控制台中输入上面的代码,你应该可以看到输出。如果您有权在当前目录中创建文件,则日志文件将被打包到当前目录中。

我希望这有帮助!

相关问题 更多 >