Python使用登录模块

时间:2022-03-09 21:59:10

I have tried to find the best way to set up logging in a module, including here, but I still cannot seem to get logging working as I expected.

我试图找到在模块中设置日志记录的最佳方法,包括此处,但我仍然无法像我预期的那样使日志记录工作。

My files are:

我的文件是:

Foo
    __init__.py
    bar.py
app.py

The contents are:

内容如下:

__init__.py

import logging

logging.getLogger(__name__).addHandler(logging.NullHandler())

bar.py

import logging

class Bar(object):
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        #self.logger.addHandler(logging.StreamHandler())
        self.logger.warning('Logger - Create bar')
        print('Print - Create bar')

app.py

from foo.bar import Bar
import logging

# create logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)

# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# add formatter to console_handler
console_handler.setFormatter(formatter)

# add console_handler to logger
logger.addHandler(console_handler)

bar = Bar()

Running app.py in this format produces no logging output.

以此格式运行app.py不会生成日志记录输出。

But if I uncomment the line in bar.py:

但如果我取消注释bar.py中的行:

self.logger.addHandler(logging.StreamHandler())

I get the logging outpt, but not formatting as app.py has defined.

我得到了日志记录,但没有像app.py定义的格式化。

Can someone please help me understand what I'm missing?

有人可以帮我理解我错过的东西吗?

2 个解决方案

#1


0  

Why should you get output?

你为什么要输出?

From the docs: NullHandler

来自文档:NullHandler

The NullHandler class, located in the core logging package, does not do any formatting or output. It is essentially a ‘no-op’ handler for use by library developers.

位于核心日志记录包中的NullHandler类不执行任何格式化或输出。它本质上是一个供库开发人员使用的“无操作”处理程序。

The formatter is applied to the logging.basicConfig() if you want to set it as general default or the the instance (like you do for console_handler).

如果要将其设置为常规默认值或实例(就像您对console_handler所做的那样),格式化程序将应用于logging.basicConfig()。

Now you just have to add it to the bar.logger.addHandler() (through a func f.e.) instead of creating a new variable in your other py file thats named the same as the member in bar.

现在你只需要将它添加到bar.logger.addHandler()(通过func f.e.),而不是在你的其他py文件中创建一个名为与bar中成员相同的新变量。

In essence: you have multiple loggers, if you print the names, you get something along:

实质上:你有多个记录器,如果你打印名称,你会得到一些东西:

Foo
__main__
Foo.bar

You only configure the Formatter of main, not the others.

您只能配置main的Formatter,而不是其他。


To debug what and if any handler/formatstrings are set:

要调试设置什么以及是否设置任何处理程序/格式字符串:

for l in logging.Logger.manager.loggerDict:
    loggr = logging.Logger.manager.loggerDict[l]
    print("Found logger: " + l)
    if loggr.handlers:
        for h in loggr.handlers:
            formr = loggr.handlers[0].formatter
            if formr:
                print("        {} {}".format(l, formr._fmt))
            else:
                print("        {} has no formatter set.".format(l))
    else:
        print("    {} has no handlers.".format(l))

#2


0  

The application should dictated the logging rather than the library, so if you want to enable the logging of foo/bar.py, you need to add a handler that is different from the NullHandler to it on app.py. The way to do it would be just to add the following line before you instantiate Bar:

应用程序应该指定日志而不是库,因此如果要启用foo / bar.py的日志记录,则需要在app.py上添加与NullHandler不同的处理程序。这样做的方法就是在实例化Bar之前添加以下行:

logging.getLogger('foo').addHandler(console_handler)

Then the logging from bar.py will be outputted using the same format you defined on app.py.

然后将使用您在app.py上定义的相同格式输出bar.py中的日志记录。

For further reference please check the hitchhiker's guide to python section about logging

如需进一步参考,请查看hitchhiker的python部分关于日志记录的指南

#1


0  

Why should you get output?

你为什么要输出?

From the docs: NullHandler

来自文档:NullHandler

The NullHandler class, located in the core logging package, does not do any formatting or output. It is essentially a ‘no-op’ handler for use by library developers.

位于核心日志记录包中的NullHandler类不执行任何格式化或输出。它本质上是一个供库开发人员使用的“无操作”处理程序。

The formatter is applied to the logging.basicConfig() if you want to set it as general default or the the instance (like you do for console_handler).

如果要将其设置为常规默认值或实例(就像您对console_handler所做的那样),格式化程序将应用于logging.basicConfig()。

Now you just have to add it to the bar.logger.addHandler() (through a func f.e.) instead of creating a new variable in your other py file thats named the same as the member in bar.

现在你只需要将它添加到bar.logger.addHandler()(通过func f.e.),而不是在你的其他py文件中创建一个名为与bar中成员相同的新变量。

In essence: you have multiple loggers, if you print the names, you get something along:

实质上:你有多个记录器,如果你打印名称,你会得到一些东西:

Foo
__main__
Foo.bar

You only configure the Formatter of main, not the others.

您只能配置main的Formatter,而不是其他。


To debug what and if any handler/formatstrings are set:

要调试设置什么以及是否设置任何处理程序/格式字符串:

for l in logging.Logger.manager.loggerDict:
    loggr = logging.Logger.manager.loggerDict[l]
    print("Found logger: " + l)
    if loggr.handlers:
        for h in loggr.handlers:
            formr = loggr.handlers[0].formatter
            if formr:
                print("        {} {}".format(l, formr._fmt))
            else:
                print("        {} has no formatter set.".format(l))
    else:
        print("    {} has no handlers.".format(l))

#2


0  

The application should dictated the logging rather than the library, so if you want to enable the logging of foo/bar.py, you need to add a handler that is different from the NullHandler to it on app.py. The way to do it would be just to add the following line before you instantiate Bar:

应用程序应该指定日志而不是库,因此如果要启用foo / bar.py的日志记录,则需要在app.py上添加与NullHandler不同的处理程序。这样做的方法就是在实例化Bar之前添加以下行:

logging.getLogger('foo').addHandler(console_handler)

Then the logging from bar.py will be outputted using the same format you defined on app.py.

然后将使用您在app.py上定义的相同格式输出bar.py中的日志记录。

For further reference please check the hitchhiker's guide to python section about logging

如需进一步参考,请查看hitchhiker的python部分关于日志记录的指南