python - 日志级别随机变化并且并不总是写入文件

标签 python logging

我有这段代码可以在 Python 中设置我的记录器:

  #Configure logging
  logging.basicConfig(format = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                      datefmt='%m-%d %H:%M',
                      filename= "log.txt",
                      level = logging.getLevelName('DEBUG'))


  print(logging.getLogger().getEffectiveLevel())

但是 print 语句的输出有时是这样的:

30

其他时候是这样的(这是正确的):

10

但通常,即使将日志记录级别设置为正确的数字,它也不会将任何内容记录到文件中,但有时它会起作用。我需要做什么来确保我的日志记录级别设置正确?

*编辑:以下是我根据@randomir 的建议的解决方案。 **编辑:我必须在调用 logging.basicConfig() 后设置级别进行第二次更改,否则日志记录级别仍然不会被一致调用。 `logging.getLogger().setLevel(...) 行现在似乎可以工作。

我创建了一个新类:Logger.py。

import logging

class Logger(object):
   def __init__(self):
     logging.basicConfig(format = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                      datefmt='%m-%d %H:%M',
                      filename= "log.txt")

     logging.getLogger().setLevel(logging.getLevelName("DEBUG"))

     print(logging.getLogger().getEffectiveLevel())

现在,我不再直接在启动类中配置基本配置,而是实例化记录器类一次:

from Logger import Logger
import logging

class LaunchPython(object):
  #Configure Logging
  Logger()

  logging.info("Application has started")

在调用记录器的所有后续类中,我只是将 importlogging 放在顶部,然后执行 logging.info(...)logging。调试(....)。无需导入 Logger.py 类并重新实例化它。

最佳答案

logging.basicConfig()为您的应用程序创建一个根记录器(即名为 root 的记录器,您可以使用 logging.getLogger('root')logging.getLogger('root') 获取它。 getLogger())。

诀窍是,在第一次调用任何日志记录函数(例如 logging.info)时,会使用默认值(例如 level=30)创建 root 记录器())(如果尚不存在)。因此,请确保在应用程序的任何其他部分进行任何日志记录之前调用 basicConfig()

您可以通过将记录器配置提取到单独的模块(例如 logger.py)来实现此目的,然后将该模块导入到每个模块中。或者,如果您的应用程序有一个中央入口点,只需在那里进行配置即可。请注意,您调用的第 3 方函数还将创建 root 记录器(如果它不存在)。

另请注意,如果您的应用程序是多线程的:

Note This function should be called from the main thread before other threads are started. In versions of Python prior to 2.7.1 and 3.2, if this function is called from multiple threads, it is possible (in rare circumstances) that a handler will be added to the root logger more than once, leading to unexpected results such as messages being duplicated in the log.

关于python - 日志级别随机变化并且并不总是写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44957262/

相关文章:

python - 在独立的 Python QGis 应用程序中加载图层/形状文件时出错

python - 属性错误 : 'module' object has no attribute 'pydebug'

java - 使用 JMS 重试机制记录异常情况

Python logger.debug 将参数转换为字符串而不记录日志

python - 我可以在 python 中使用字符串作为命名参数吗

python - 使用map和setattr函数动态设置对象属性

javascript - winston 超过 maxsize 后我的日志文件不旋转

bash - 记录到文件 gnome 终端输出

logging - 无法使用基于日志的指标(指标类型 : "Counter")

python - 如何解决雅虎数据问题?容量不足,无法填充