python - 使用 Python 进行日志记录。处理程序和控制台副本

标签 python logging

我有一个简单的日志记录设置:

def main()

  # ....
  # Create logger
  logging.basicConfig(filemode='w', level=logging.DEBUG)
  logger = logging.getLogger(__name__)
  logger.setLevel(logging.DEBUG)

  # Create file handler for DEBUG and above
  fh1 = logging.FileHandler(__name__ + '.debug.log')
  fh1.setLevel(logging.DEBUG)

  # Create file handler for INFO and above
  fh2 = logging.FileHandler(__name__ + '.info.log')
  fh2.setLevel(logging.INFO)

  # Create console handler with INFO and above
  ch = logging.StreamHandler()
  ch.setLevel(logging.INFO)

  # Add all the handlers to the logger
  logger.addHandler(fh1)
  logger.addHandler(fh2)
  logger.addHandler(ch)
  # ....

然后当我打电话时

logger.info("this is an INFO message")
logger.debug("this is a DEBUG message")

我在控制台上得到以下信息:

this is an INFO message
INFO:__main__:this is an INFO message
this is a DEBUG message
DEBUG:__main__:this is a DEBUG message

尽管我预计只会在控制台中看到 INFO 消息(因为我在上面为 StreamHandler 指定了 logging.info)。为什么我会收到这些重复项?

我的 .debug.loginfo.log 文件仅包含正确级别的消息,但它们的格式不包含前缀 INFO:_​​_main__ 也不是DEBUG:__main__。为什么它们的格式不同?

最佳答案

logging.basicConfig(filemode='w', level=logging.DEBUG)

创建一个StreamHandler。因此,您的代码将创建两个 StreamHandlers,一个具有日志记录级别 DEBUG,另一个具有日志记录级别 INFO

basicConfig 是一个便利函数。如果您想创建自己的处理程序,则无需调用 basicConfig。 (或者您可以调用 basicConfig 并添加其他处理程序...)

<小时/>

如果您在调用 basicConfig 时未提供文件名,则会将 StreamHandler 添加到根记录器中。这是代码inside the basicConfig function :

if handlers is None:
    filename = kwargs.get("filename")
    if filename:
        mode = kwargs.get("filemode", 'a')
        h = FileHandler(filename, mode)
    else:
        stream = kwargs.get("stream")
        h = StreamHandler(stream)

关于python - 使用 Python 进行日志记录。处理程序和控制台副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24540479/

相关文章:

python - 枚举后需要逗号才能正确输出要列出的值

python - 与 Pandas 匹配的单数和复数单词

git log over 在使用 --follow 时限制输出?

python - 用于 Python 应用程序的 Bluemix 日志记录

python - Python 中的束搜索

python - 使用 python 通过网络将数据发送到远程程序

python - 运行一个可执行文件,等待它产生输出,运行另一个程序

php - 使用 PHP 将用户名放入 apache access_log 且不使用 HTTP 身份验证

logging - 是否可以在运行时更改 AWS Lambda 的日志级别?

java - Log4j2 - 找到配置,但无法正常工作