Python 自定义日志记录不遵循定义的格式化程序样式



我有一个用python(3.5(定义的自定义记录器配置文件,如下所示:

# 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")

我希望这个日志记录应该已经打印 - 时间,日志级别,包名称,主机名,然后消息为在此行中配置"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"配置为custom_logger.py

但它只是打印this is my error message我需要在我的配置中更改什么才能在日志中吐出所有 elemnet?

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

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
    }
  } 
})

最新更新