Journalctl:将_SYSTEMD_UNIT字段添加到日志打印输出中

使用命令:

/ usr / bin / journalctl -o short -f | ncat {some-ip} {some port}

将日志输出转发到某个远程日志跟踪应用程序。

问题在于,我在打印输出中缺lesssystemd单元/服务名称,很难确定哪个服务会产生什么日志行。

例如这是一个nginx行:

Jun 25 07:51:09 localhost bash [497] :10.23.132.98 – – [25 / Jun / 2014:07:51:09 +0000]“GET /page.html HTTP / 1.1”200 321“https:// {ip}“”Mozilla / 5.0(Windows NT 6.1; WOW64)AppleWebKit / 537.36(KHTML,像Gecko)Chrome / 35.0.1916.153 Safari / 537.36“

在日志中有bash [497] – 进程的PID。 我怎样才能把更多的数据添加到日志? 例如,该PID的docker容器名称或systemd服务/单元名称?

不要使用-o short ,它会消除信息!

尝试-o json-o verbose

Python可以做到这一点:

 from systemd import journal j = journal.Reader() j.this_boot() j.add_match(_SYSTEMD_UNIT="newnginx.service") for entry in j: print('{} {}'.format(entry['_SYSTEMD_UNIT'], entry['MESSAGE'])) 

(在CentOS 7上的python)

最后,我以不同的方式实现了这一点

每个服务/系统单元都有一个post执行脚本,它使用:

/ usr / bin / journalctl -u {单位名称} -o short -f | sed's / ^ / {unit name} /'| ncat {some-ip} {some port}

现在我有在日志行的开始单位名称! 而我的日志收集器在消息中有单元名称!

journalctl -u mongodb.service -o short -f | sed's / ^ / mongodb.service /'| ncat {some-ip} {some port}

会输出:

mongodb Jun 26 09:11:35 localhost bash [1710]:2014-06-26T09:11:35.714 + 0000 [rsHealthPoll] replset info mongodb-0:27017心跳失败,重试