在我正在编写的python脚本中,我试图使用日志模块记录事件。我有以下代码来配置我的记录器:

ERROR_FORMAT = "%(levelname)s at %(asctime)s in %(funcName)s in %(filename) at line %(lineno)d: %(message)s"
DEBUG_FORMAT = "%(lineno)d in %(filename)s at %(asctime)s: %(message)s"
LOG_CONFIG = {'version':1,
              'formatters':{'error':{'format':ERROR_FORMAT},
                            'debug':{'format':DEBUG_FORMAT}},
              'handlers':{'console':{'class':'logging.StreamHandler',
                                     'formatter':'debug',
                                     'level':logging.DEBUG},
                          'file':{'class':'logging.FileHandler',
                                  'filename':'/usr/local/logs/DatabaseUpdate.log',
                                  'formatter':'error',
                                  'level':logging.ERROR}},
              'root':{'handlers':('console', 'file')}}
logging.config.dictConfig(LOG_CONFIG)

当我尝试运行logging.debug(“一些字符串”)时,我没有得到控制台的输出,尽管文档中的这一页说logging.debug应该让根记录器输出消息。为什么我的程序不输出任何东西,我该如何修复它?


当前回答

试试这个?似乎在删除我的案例中的所有处理程序后,问题就解决了。

for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)

logging.basicConfig(filename='output.log', level=logging.INFO)

其他回答

这对我来说很好……

import logging

LOGGER = logging.getLogger("my-fetcher")
logging.basicConfig(level=logging.INFO)

LOGGER.info("Established Connection Successfully!")
# > INFO:my-fetcher:Established Connection Successfully!

对于这里想要一个超级简单的答案的任何人:设置你想要显示的级别。在我所有脚本的顶部,我只是放:

import logging
logging.basicConfig(level = logging.INFO)

然后显示在该级别或以上的任何内容:

logging.info("Hi you just set your fleeb to level plumbus")

它是一个有五个级别的分层集,因此日志将显示在您设置的级别或更高的级别。因此,如果想要显示错误,可以使用日志记录。错误(“plumbus is broken”)。

级别由高到低依次为:DEBUG、INFO、WARNING、ERROR和CRITICAL。默认设置为WARNING。

这是一篇很好的文章,包含了比我的回答更好的信息: https://www.digitalocean.com/community/tutorials/how-to-use-logging-in-python-3

许多年后,Python日志记录器似乎仍然存在可用性问题。下面是一些解释和例子:

import logging
# This sets the root logger to write to stdout (your console).
# Your script/app needs to call this somewhere at least once.
logging.basicConfig()

# By default the root logger is set to WARNING and all loggers you define
# inherit that value. Here we set the root logger to NOTSET. This logging
# level is automatically inherited by all existing and new sub-loggers
# that do not set a less verbose level.
logging.root.setLevel(logging.NOTSET)

# The following line sets the root logger level as well.
# It's equivalent to both previous statements combined:
logging.basicConfig(level=logging.NOTSET)


# You can either share the `logger` object between all your files or the
# name handle (here `my-app`) and call `logging.getLogger` with it.
# The result is the same.
handle = "my-app"
logger1 = logging.getLogger(handle)
logger2 = logging.getLogger(handle)
# logger1 and logger2 point to the same object:
# (logger1 is logger2) == True

logger = logging.getLogger("my-app")
# Convenient methods in order of verbosity from highest to lowest
logger.debug("this will get printed")
logger.info("this will get printed")
logger.warning("this will get printed")
logger.error("this will get printed")
logger.critical("this will get printed")


# In large applications where you would like more control over the logging,
# create sub-loggers from your main application logger.
component_logger = logger.getChild("component-a")
component_logger.info("this will get printed with the prefix `my-app.component-a`")

# If you wish to control the logging levels, you can set the level anywhere 
# in the hierarchy:
#
# - root
#   - my-app
#     - component-a
#

# Example for development:
logger.setLevel(logging.DEBUG)

# If that prints too much, enable debug printing only for your component:
component_logger.setLevel(logging.DEBUG)


# For production you rather want:
logger.setLevel(logging.WARNING)

一个常见的混淆来源是一个初始化不好的根日志记录器。考虑一下:

import logging
log = logging.getLogger("myapp")
log.warning("woot")
logging.basicConfig()
log.warning("woot")

输出:

woot
WARNING:myapp:woot

根据您的运行时环境和日志级别,第一行日志(在基本配置之前)可能不会出现在任何地方。

默认日志级别为warning。 因为您没有更改级别,所以根日志记录器的级别仍然是警告。 这意味着它将忽略级别低于警告的任何日志记录,包括调试日志记录。

这在教程中有解释:

import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything

'info'行不打印任何东西,因为级别比info高。

要更改级别,只需在根日志记录器中设置它:

'root':{'handlers':('console', 'file'), 'level':'DEBUG'}

换句话说,用level=DEBUG定义处理程序是不够的,实际的日志级别也必须是DEBUG,以便让它输出任何东西。

导入日志 log = logging.getLogger() log.setLevel (logging.DEBUG)

这段代码将默认日志级别设置为DEBUG。