如何在python中的YAML文件中设置logging.handlers.SysLogHandler的输出

时间:2016-08-30 10:23:32

标签: python logging yaml syslog

我有以下配置文件:

[loggers]
keys=MYLogger

[handlers]
keys=fileHandler,streamHandler,sysHandler

[formatters]
keys=simpleFormatter

[logger_MYLogger]
level=INFO
handlers=fileHandler
qualname=MYLogger
propagate=0

[handler_fileHandler]
class=FileHandler
formatter=simpleFormatter
args=('mylog.log',)

[handler_streamHandler]
class=StreamHandler
formatter=simpleFormatter
args=(sys.stdout,)

[handler_sysHandler]
class=logging.handlers.SysLogHandler
formatter=simpleFormatter
args=('/dev/log',)


[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s : %(message)s
datefmt=%Y-%m-%d %H:%M:%S

我需要将其转换为YAML文件。我成功完成了它,除了sysHandler的一部分:

  version: 1
  formatters:
    simpleFormatter:
      format: '%(asctime)s - %(name)s - %(levelname)s : %(message)s'
      datefmt: '%Y-%m-%d %H:%M:%S'
  handlers:
    stream:
      class: logging.StreamHandler
      formatter: simpleFormatter
      stream: ext://sys.stdout
    file:
      class: logging.FileHandler
      formatter: simpleFormatter
      filename: mylog.log
    # sys:
    #   class: logging.handlers.SysLogHandler
    #   formatter: simpleFormatter
    #   stream: /dev/log
  loggers: 
    MYLogger:
      level: INFO
      handlers: [stream, file]

如何以yaml格式为sysHandler提供参数?为什么只需将args放在原始配置文件中就可以了,这里我必须指定stream / filename?

1 个答案:

答案 0 :(得分:1)

日志记录dictionary schema details有关于处理程序的以下内容:

handlers - the corresponding value will be a dict in which each key is a handler 
id and each value is a dict describing how to configure the corresponding Handler
instance.

The configuring dict is searched for the following keys:

    class (mandatory). This is the fully qualified name of the handler class.
    level (optional). The level of the handler.
    formatter (optional). The id of the formatter for this handler.
    filters (optional). A list of ids of the filters for this handler.

All other keys are passed through as keyword arguments to the handler’s
constructor.

SysLogHandler具有以下signature

SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)

stream(不是处理程序的必需键或可选键)作为关键字参数传递给SysLogHandler(),并且不是可用于实例化该类实例的关键字

StreamHandler(即stream)和FileHandler(即filename)的非强制性/可选密钥与各自的签名相匹配。

我假设您真的需要提供以tuple参数作为序列来提供地址,以使其被接受:

sys:
    class: logging.handlers.SysLogHandler
    formatter: simpleFormatter
    address: [localhost, /dev/log]

(请注意,INI样式配置文件中args的{​​{1}}条目应以元组开头。来自logging documentation

[handler_sysHandler]