Python 3.5.2 记录器配置和使用

标签 python python-3.x logging

我是 python 的新手,正在尝试在我的简单应用程序中设置一个记录器。

这是应用结构:

 - checker
      - checking
         - proxy_checker.py
      - custom_threading
         - __init__.py
         - executor_my.py
         - long_task.py
      - tests
      - __init__.py
      - logging_config.ini
      - main.py

我正在尝试设置文件配置记录器 在主模块的 checker/__init__.py:

from logging.config import fileConfig

fileConfig('logging_config.ini')

logging_config.ini

[loggers]
keys=root

[handlers]
keys=stream_handler

[formatters]
keys=formatter

[logger_root]
level=DEBUG
handlers=stream_handler

[handler_stream_handler]
class=StreamHandler
level=DEBUG
formatter=formatter
args=(sys.stderr,)

[formatter_formatter]
format=%(asctime)s %(name)-12s %(levelname)-8s %(message)s

并在 /checker/custom_threading/exector_my.py 中使用它:

import concurrent.futures
import logging

from custom_threading.long_task import LongTask


class MyExecutor(object):
    logger = logging.getLogger(__name__)
    _executor = concurrent.futures.ThreadPoolExecutor(max_workers=500)

    def __init__(self, thread_count, task):
        self._thread_count = thread_count
        self._task = LongTask(task)
        pass

    def start(self):
        self.logger.debug("Launching with thread count: " + str(self._thread_count))

*more irrelevant code*

尝试使用 logger.info/logger.debug。 对于这两个选项,我都没有收到任何错误,控制台中也没有记录任何内容。我做错了什么?

附言也许我在 Win 10 x64 上运行它也很有用

最佳答案

我的(可能是错误的 :-)猜测是您通过 python checker/main.py 之类的东西启动脚本,因此 __init__.py 中的日志配置是未执行。

请看一下这个答案: Why is __init__.py not being called?

此外,您需要确保在getLogger() 之前调用fileConfig()(类主体在导入时执行)。一个有效的设置是在 main.py 开头的某处加载配置,并在 MyExecutor.__init__() 中实例化记录器。

关于Python 3.5.2 记录器配置和使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39976715/

相关文章:

python - 返回给定字符串语言的最佳方法

Python:如何将自定义类成员与内置类型进行比较

java - 在log4j2配置文件中使用pom.xml SystemProperty

php - 我应该在这里使用委托(delegate)吗?

python - Python方式为一维数组中的每个元素在第三维创建新的二维数组

python - 打印两个列表中的值对

python - Boost Python,Visual Studio 链接到错误的 boost dll

python - 使用 for 循环创建圣诞树

java - 仅在父类(super class)/抽象类中声明 slf4j 记录器并在所有子类中使用它是好的做法吗?

python - wxPython 中的按钮事件出现错误