我希望rsyslog以JSON格式编写日志消息,这需要在string周围使用双引号(“)。
问题是有些时候值包括双引号本身,而那些需要逃避 – 但我不知道如何做到这一点。
目前我的rsyslog.conf包含这个格式,我使用(有点简化):
$template JsonFormat,"{\"msg\":\"%msg%\",\"app-name\":\"%app-name%\"}\n",sql
但是当包含双引号的消息到达时,JSON被破坏,例如:
user pid=21214 uid=0 auid=4294967295 msg='PAM setcred: user="oracle" exe="/bin/su" (hostname=?, addr=?, terminal=? result=Success)'
变成:
{"msg":"user pid=21214 uid=0 auid=4294967295 msg='PAM setcred: user="oracle" exe="/bin/su" (hostname=?, addr=?, terminal=? result=Success)'","app-name":"user"}
但是我需要的是:
{"msg":"user pid=21214 uid=0 auid=4294967295 msg='PAM setcred: user=\"oracle\" exe=\"/bin/su\" (hostname=?, addr=?, terminal=? result=Success)'","app-name":"user"}
作为rsyslog 4.6.2,似乎你可以只使用json属性选项:
$template JsonFormat,"{\"msg\":\"%msg:::json%\",\"app-name:::json\":\"%app-name:::json%\"}\n",sql
在这里看到更多的细节。
我发现了一个非常难看的解决办法,我很乐意用一些合理的东西取而代之:
$template JsonFormat,"{\"rawmsg\":\"%rawmsg:R,BRE,1,BLANK,0:\([^\"]*\)\"*--end%%rawmsg:R,BRE,1,BLANK,1:\([^\"]*\)\"--end%%rawmsg:R,BRE,1,BLANK,2:\([^\"]*\)\"--end%%rawmsg:R,BRE,1,BLANK,3:\([^\"]*\)\"--end%%rawmsg:R,BRE,1,BLANK,4:\([^\"]*\)\"--end%%rawmsg:R,BRE,1,BLANK,5:\([^\"]*\)\"--end%%rawmsg:R,BRE,1,BLANK,6:\([^\"]*\)\"--end%%rawmsg:R,BRE,1,BLANK,7:\([^\"]*\)\"--end%%rawmsg:R,BRE,1,BLANK,8:\([^\"]*\)\"--end%%rawmsg:R,BRE,1,BLANK,9:\([^\"]*\)\"--end%\",\"msg\":\"%msg:R,BRE,1,BLANK,0:\([^\"]*\)\"*--end%%msg:R,BRE,1,BLANK,1:\([^\"]*\)\"--end%%msg:R,BRE,1,BLANK,2:\([^\"]*\)\"--end%%msg:R,BRE,1,BLANK,3:\([^\"]*\)\"--end%%msg:R,BRE,1,BLANK,4:\([^\"]*\)\"--end%%msg:R,BRE,1,BLANK,5:\([^\"]*\)\"--end%%msg:R,BRE,1,BLANK,6:\([^\"]*\)\"--end%%msg:R,BRE,1,BLANK,7:\([^\"]*\)\"--end%%msg:R,BRE,1,BLANK,8:\([^\"]*\)\"--end%%msg:R,BRE,1,BLANK,9:\([^\"]*\)\"--end%\",\"hostname\":\"%hostname%\",\"fromhost\":\"%fromhost%\",\"syslogtag\":\"%syslogtag%\",\"programname\":\"%programname%\",\"priority\":\"%pri%\",\"priority-text\":\"%PRI-text%\",\"infounittype\":\"%iut%\",\"syslogfacility\":\"%syslogfacility%\",\"syslogfacility-text\":\"%syslogfacility-text%\",\"syslogseverity\":\"%syslogseverity%\",\"syslogseverity-text\":\"%syslogseverity-text%\",\"timegenerated\":\"%timegenerated%\",\"timereported\":\"%timereported%\",\"app-name\":\"%app-name%\",\"procid\":\"%procid%\",\"msgid\":\"%msgid%\"}\n"
它的function是用正则expression式将string分割成几部分,然后将它们与删除的双引号粘贴在一起 – 也仅限于消息中的10个双引号。