如何在多个模块中使用python日志记录 [英] How to use python logging in multiple modules

查看:295
本文介绍了如何在多个模块中使用python日志记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在Python应用程序中执行日志记录的标准设置是什么.

I was wondering what the standard set up is for performing logging from within a Python app.

我正在使用Logging类,并且已经编写了自己的logger类来实例化Logging类.然后我的主实例化我的记录器包装器类.但是,我的main实例化了其他类,我希望这些其他类也能够通过main中的logger对象写入他的日志文件.

I am using the Logging class, and I've written my own logger class that instantiates the Logging class. My main then instantiates my logger wrapper class. However, my main instantiates other classes and I want those other classes to also be able to write to he log file via the logger object in the main.

如何使该记录器对象可以被其他类调用?几乎就像我们需要某种静态logger对象才能使其正常工作.

How do I make that logger object such that it can be called by other classes? It's almost like we need some sort of static logger object to get this to work.

我想问题的长短是:如何在代码结构中实现日志记录,以便从main内部实例化的所有类都可以写入同一日志文件?我是否只需要在每个指向相同文件的类中创建一个新的日志记录对象?

I guess the long and short of the question is: how do you implement logging within your code structure such that all classes instantiated from within main can write to the same log file? Do I just have to create a new logging object in each of the classes that points to the same file?

推荐答案

我不知道您所说的Logging类是什么意思-Python的内置日志记录中没有这样的类.您实际上并不需要包装器:这是一个如何从您编写的任意类中进行日志记录的示例:

I don't know what you mean by the Logging class - there's no such class in Python's built-in logging. You don't really need wrappers: here's an example of how to do logging from arbitrary classes that you write:

import logging

# This class could be imported from a utility module
class LogMixin(object):
    @property
    def logger(self):
        name = '.'.join([__name__, self.__class__.__name__])
        return logging.getLogger(name)


# This class is just there to show that you can use a mixin like LogMixin
class Base(object):
    pass

# This could be in a module separate from B
class A(Base, LogMixin):
    def __init__(self):
        # Example of logging from a method in one of your classes
        self.logger.debug('Hello from A')

# This could be in a module separate from A
class B(Base, LogMixin):
    def __init__(self):
        # Another example of logging from a method in one of your classes
        self.logger.debug('Hello from B')

def main():
    # Do some work to exercise logging
    a = A()
    b = B()
    with open('myapp.log') as f:
        print('Log file contents:')
        print(f.read())

if __name__ == '__main__':
    # Configure only in your main program clause
    logging.basicConfig(level=logging.DEBUG,
                        filename='myapp.log', filemode='w',
                        format='%(name)s %(levelname)s %(message)s')
    main()

通常不需要在类级别使用记录器:在Python中,与Java不同,程序(分解)组成的单元是模块.但是,正如我上面显示的那样,没有什么可以阻止您执行此操作.该脚本在运行时显示:

Generally it's not necessary to have loggers at class level: in Python, unlike say Java, the unit of program (de)composition is the module. However, nothing stops you from doing it, as I've shown above. The script, when run, displays:

Log file contents:
__main__.A DEBUG Hello from A
__main__.B DEBUG Hello from B

请注意,两个类中的代码都记录到了同一个文件myapp.log中.即使在不同的模块中使用A和B也可以使用.

Note that code from both classes logged to the same file, myapp.log. This would have worked even with A and B in different modules.

这篇关于如何在多个模块中使用python日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆