扩展 Python 记录器

发布于 2024-12-02 16:14:27 字数 674 浏览 0 评论 0原文

我正在寻找一种简单的方法来扩展标准 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 语句表示是否也打印日志到标准输出。

我已经看到了一些覆盖记录器类

但我对这门语言很陌生,并没有真正了解正在发生的事情,或者如何实现这个想法。任何帮助将不胜感激:)

I'm looking for a simple way to extend the logging functionality defined in the standard python library. I just want the ability to choose whether or not my logs are also printed to the screen.

Example: Normally to log a warning you would call:

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

This sets the configurations of the log and puts the warning into the log

I would like to have something along the lines of a call like:

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

where the True statement signifys if the log is also printed to stdout.

I've seen some examples of implementations of overriding the logger class

but I am new to the language and don't really follow what is going on, or how to implement this idea. Any help would be greatly appreciated :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

遗失的美好 2024-12-09 16:14:27

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,您可以在交互式控制台中键入上述代码,您应该会看到输出。如果您有权在当前目录中创建文件,则日志文件将被打包在当前目录中。

我希望这有帮助!

The Python logging module defines these classes:

Loggers that emit log messages.
Handlers that put those messages to a destination.
Formatters that format log messages.
Filters that filter log messages.

A Logger can have Handlers. You add them by invoking the addHandler() method. A Handler can have Filters and Formatters. You similarly add them by invoking the addFilter() and setFormatter() methods, respectively.

It works like this:

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)

Now, you can use this object like this:

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

If you just run python on your machine, you can type the above code into the interactive console and you should see the output. The log file will get crated in your current directory, if you have permissions to create files in it.

I hope this helps!

耳根太软 2024-12-09 16:14:27

可以重写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.")

It is possible to override logging.getLoggerClass() to add new functionality to loggers. I wrote simple class which prints green messages in stdout.

Most important parts of my code:

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.")
葬シ愛 2024-12-09 16:14:27

处理程序将日志记录(由记录器创建)发送到适当的位置
目的地。

(来自文档: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) 行表示此特定处理程序将获取 DEBUG 或更高级别的日志消息。您可能希望将其设置为“警告”或更高,因为您只想将更重要的内容发送到控制台。因此,您的日志记录将像这样工作:

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

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

(from the docs: http://docs.python.org/library/logging.html)

Just set up multiple handlers with your logging object, one to write to file, another to write to the screen.

UPDATE

Here is an example function you can call in your classes to get logging set up with a handler.

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)

You would just need to set up another handler for files, ala the StreamHandler code that's already there, and add it to the logging object. The line that says ch.setLevel(logging.DEBUG) means that this particular handler will take logging messages that are DEBUG or higher. You'll likely want to set yours to WARNING or higher, since you only want the more important things to go to the console. So, your logging would work like this:

self.log.info("Hello, World!") -> goes to file
self.log.error("OMG!!") -> goes to file AND console
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文