我尝试使用 logging.handlers.SysLogHandler 进行日志记录并将其发送到 logstash。
python 代码:
import logging
from logging import handlers
# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = handlers.SysLogHandler(facility=handlers.SysLogHandler.LOG_AUTH)
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
logger.info('go')
日志配置:
input {
syslog {
}
}
output {
stdout {codec => rubydebug {}}
}
输出日志:
{
"message" => "<38>2014-09-03 12:48:36,700 - simple_example - INFO - go\u0000",
"@version" => "1",
"@timestamp" => "2014-09-03T12:48:36.702Z",
"host" => "127.0.0.1",
"tags" => [
[0] "_grokparsefailure"
],
"priority" => 13,
"severity" => 5,
"facility" => 1,
"facility_label" => "user-level",
"severity_label" => "Notice"
}
但是,如果我改变了 factory=handlers.SysLogHandler.LOG_DAEMON
不改变输出logstash:
{
"message" => "<30>2014-09-03 12:51:52,307 - simple_example - INFO - go\u0000",
"@version" => "1",
"@timestamp" => "2014-09-03T12:51:52.307Z",
"host" => "127.0.0.1",
"tags" => [
[0] "_grokparsefailure"
],
"priority" => 13,
"severity" => 5,
"facility" => 1,
"facility_label" => "user-level",
"severity_label" => "Notice"
}
我如何更改:设施、严重性、优先级、设施标签、严重性标签?
很可能是因为 Python 没有添加此信息:
output {
stdout {}
}
2014-09-03T13:19:14.862+0000 127.0.0.1 <30>2014-09-03 13:19:14,860 - simple_example - INFO - go
但是怎么添加呢?
最佳答案
查看 logging.handlers 的文档:
facility
。上面链接的文档中列出了允许的级别:ch = handlers.SysLogHandler(facility=handlers.SysLogHandler.LOG_AUTH, facility=LOG_LOCAL0)
priority
从日志级别映射,该级别由消息发送者 logger.warn()
vs logger.info()
等设置。 mapPriority
的文档指出,“默认算法将 DEBUG、INFO、WARNING、ERROR 和 CRITICAL 映射到等效的系统日志名称,以及所有其他级别'警告'的名称。”