Linux
rsyslog - 模板 - 用於插入數據庫的正則表達式數據
在過去的幾天裡,我一直在Google搜尋,尋找一個可靠的例子,說明如何對所需數據的日誌條目進行正則表達式,然後將其插入數據庫,但顯然我的 google-fu 缺少。
我要做的是跟踪電子郵件何時發送,然後跟踪遠端 mta 響應,特別是 dsn 程式碼。此時我為每種情況設置了兩個模板:
# /etc/rsyslog.conf ... $Template tpl_custom_header, "MPurcell: CUSTOM HEADER Template: %msg%\n" $Template tpl_response_dsn, "MPurcell: RESPONSE DSN Template: %msg%\n" # /etc/rsyslog.d/mail if $programname == 'mail-myapp' then /var/log/mail/myapp.log if ($programname == 'mail-myapp') and ($msg contains 'X-custom_header') then /var/log/mail/test.log;tpl_custom_header if ($programname == 'mail-myapp') and ($msg contains 'dsn=') then /var/log/mail/test.log;tpl_response_dsn & ~
範例日誌條目:
MPurcell: CUSTOM HEADER Template: D921940A1A: prepend: header X-custom_header: 101 from localhost[127.0.0.1]; from=<noreply@myapp.com> to=<me@gmail.com> proto=ESMTP helo=<localhost>: headername: message-id MPurcell: RESPONSE DSN Template: D921940A1A: to=<me@gmail.com>, relay=gmail-smtp-in.l.google.com[2607:f8b0:400e:c02::1a]:25, delay=2, delays=0.12/0.01/0.82/1.1, dsn=2.0.0, status=sent (250 2.0.0 OK 1372378600 o4si2828280pac.279 - gsmtp)
我想從 CUSTOM HEADER 模板中提取:D921940A1A 和 X-custom_header 值;101
從我想提取的響應 DSN 模板中:D921940A1A 和“dsn=2.0.0”
如果有人最終面臨同樣的情況,這就是我最終要做的事情:
# /etc/rsyslog.conf # Not sure what R signifies but saw it in other examples # ERE = extended regex # 0 = The submatch we want # DFLT = How should a non match be returned? $Template tpl_custom_header, "%msg:R,ERE,0,DFLT:[^:]+--end% | %msg:R,ERE,2,DFLT:X-custom_header:( )([0-9]*)--end%\n" $Template tpl_response_dsn, "%msg:R,ERE,0,DFLT:[^:]+--end% | %msg:R,ERE,1,DFLT:dsn=([0-9][.][0-9][.][0-9])--end% \n"
要測試您的正則表達式,您應該使用:http : //www.rsyslog.com/regex/,它有點做作,但可以完成工作。
範例原始日誌條目,與 OP 略有不同:
Jun 29 05:40:28 service1 mail-myapp/cleanup[22200]: 6F67240A1A: prepend: header X-custom_header: 136 from localhost[127.0.0.1]; from=<noreply@myapp.com> to=<me@gmail.com> proto=ESMTP helo=<localhost>: headername: message-id Jun 29 05:40:30 service1 mail-myapp/smtp[22201]: 6F67240A1A: to=<me@gmail.com>, relay=gmail-smtp-in.l.google.com[2607:f8b0:400e:c01::1a]:25, delay=2, delays=0.09/0/0.82/1, dsn=2.0.0, status=sent (250 2.0.0 OK 1372485254 rs6si5760686pbc.32 - gsmtp)
應用模板後的樣子:
6F67240A1A | 136 6F67240A1A | 2.0.0
當我插入 mysql 時,我將插入 dsn 作為 int vs string 以獲得更好的性能,所以考慮使用這個:
insert into response_log_dsn set mail_id = '6F67240A1A', dsn = (select cast(replace('2.0.0', '.', '') as unsigned));