【问题标题】:Python custom logging is not following the defined formatter stylePython 自定义日志记录不遵循定义的格式化程序样式
【发布时间】:2017-02-06 15:25:41
【问题描述】:

我在python(3.5)中定义了一个自定义的logger配置文件,如下:

# custom_logger.py
import logging
import socket
import logging.config
from xyz import LOG_LEVEL

class HostIdentifier(logging.Filter):
  """
  Get host identifier
  """
  def filter(self):
   return socket.gethostname()

# https://docs.python.org/3.5/library/logging.config.html#dictionary-schema-details
logging.config.dictConfig({
  "version": 1,
  "filters": {
    "host_name": {
      "()": HostIdentifier
    },
  },
  "disable_existing_loggers": False,
  "formatters": { 
    "standard": { 
      "format": "[%(asctime)s] _message_type=%(levelname)-8s _package_name=[%(name)-12s] _host_name=[%(host_name)s] %(message)s",
      "datefmt": "%Y-%m-%d %H:%M:%S %z"
    }
  },
  "handlers": { 
    "default": { 
      "level": LOG_LEVEL,
      "filters": ["host_name"],
      "formatter": "standard",
      "class": "logging.StreamHandler",
    }
  }
})

logger = logging.getLogger("my-custom-log")


==============================

# main.py

from custom_logger import logger

logger.error("this is my error message")

我希望此日志记录应该打印 - 时间、日志级别、包名称、主机名,然后消息为 在 custom_logger.py 中的这一行 "format": "[%(asctime)s] _message_type=%(levelname)-8s _package_name=[%(name)-12s] _host_name=[%(host_name)s] %(message)s", "datefmt": "%Y-%m-%d %H:%M:%S %z" 配置

但它只是打印 this is my error message 我需要在我的配置中进行哪些更改才能让所有 elemnets 在日志中吐出?

【问题讨论】:

  • 可能需要指定何时使用default 处理程序?喜欢"root": { 'handlers': ['default'] }?
  • 不,那没有用。不过我修好了。

标签: python python-3.x logging


【解决方案1】:

我通过如下更改来修复它:

class HostIdentifier(logging.Filter):
  """
  Get host identifier
  """
  def filter(self, record):
    record.host_name = socket.gethostname()
    return True

# https://docs.python.org/3.5/library/logging.config.html#dictionary-schema-details
logging.config.dictConfig({
  "version": 1,
  "filters": {
    "host_name": {
      "()": HostIdentifier
    },
  },
  "disable_existing_loggers": False,
  "formatters": { 
    "standard": { 
      "format": "[%(asctime)s] _message_type=%(levelname)-8s _package_name=[%(name)-12s] _host_name=[%(host_name)s] %(message)s",
      "datefmt": "%Y-%m-%d %H:%M:%S %z"
    }
  },
  "handlers": { 
    "default": { 
      "level": LOG_LEVEL,
      "filters": ["host_name"],
      "formatter": "standard",
      "class": "logging.StreamHandler",
    }
  },
  "loggers": {
    "": { 
      "handlers": ["default"],
      "level": LOG_LEVEL,
      "propagate": True
    }
  } 
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 2018-12-08
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    相关资源
    最近更新 更多