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

时间:2017-02-06 15:25:41

标签: python python-3.x logging

我有一个在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")

我希望这个日志记录应该有打印时间,日志级别,包名称,主机名,然后是消息 在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我需要在配置中更改什么才能让所有elemnet在日志中吐出来?

1 个答案:

答案 0 :(得分:0)

我修改了它,如下所示:

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