Chinaunix

标题: nginx的日志格式字段替换 [打印本页]

作者: opiopuiopoi    时间: 2016-05-17 14:27
标题: nginx的日志格式字段替换
本帖最后由 opiopuiopoi 于 2016-05-17 14:32 编辑

大家熟悉的nginx的配置文件中,日志格式的片段:

log_format     main  '$remote_addr,$remote_user,[$time_local],"$request",'
                      '$status $body_bytes_sent,"$http_referer",
                       "$request_time"'
;

想把蓝色字体的字段替换为我想要的格式,红色的保留。

比如替换为:

log_format  main '$remote_addr $remote_user [$time_local] "http://$host" "$request" '
                          '$status $body_bytes_sent "$http_referer" "$http_user_agent" "$HTTP_X_UP_CALLING_LINE_ID"
';


总之原来的格式字段不固定,行数也不固定,替换为我想要的格式。
作者: lll1985911    时间: 2016-05-17 14:50
本帖最后由 lll1985911 于 2016-05-17 15:04 编辑
  1. paste -d' ' -s a.txt | sed -r -e 's/ +/ /g' -e 's/,/ "http:\/\/$host" /3' -e 's/,/ "$http_user_agent"/5' -e 's/request_time/HTTP_X_UP_CALLING_LINE_ID/' -e 's/,/ /g' -e "s/' '/'\n\t\t'/"
复制代码

作者: opiopuiopoi    时间: 2016-05-17 15:44
感谢回复!
可能是我没说清楚,再解释一下:
蓝色字体的具体字段内容我们完全没有必要管它,我们只是替换它。
paste命令的方式也不妥,因为我贴出的文本只是nginx.conf 里的一个片段,paste 一个文件就没有必要了。

回复 2# lll1985911


   
作者: lll1985911    时间: 2016-05-17 16:22
回复 3# opiopuiopoi

你要替换成什么东西?
作者: opiopuiopoi    时间: 2016-05-17 17:36
sed -e ':label; /log_format\s*main/,/;/ { /;/! { $! { N; b label }; }; s/log_format.*;/abcasdfasdfa/; }' a.txt

这个暂时完成了替换。
作者: sunzhiguolu    时间: 2016-05-17 17:38
回复 5# opiopuiopoi
能说下思路吗? 谢谢...

   
作者: moperyblue    时间: 2016-05-22 18:12
本帖最后由 moperyblue 于 2016-05-22 18:15 编辑
  1. more my_fmt.txt
  2. '$remote_addr $remote_user [$time_local] "http://$host" "$request" '
  3.                           '$status $body_bytes_sent "$http_referer" "$http_user_agent" "$HTTP_X_UP_CALLING_LINE_ID" ';
  4.                           
  5. more file
  6. xx
  7. log_format     main  '$remote_addr,$remote_user,[$time_local],"$request",'
  8.                       '$status $body_bytes_sent,"$http_referer",
  9.                        "$request_time"';
  10. oo

  11. sed  '/log_format\s*main\s*/{s//&\n/;:a;N;/;/!{s/\n//2;ta};s/\n.*//;h;s/.*/cat my_fmt.txt/e;x;G;s/\n//}' file
  12. xx
  13. log_format     main  '$remote_addr $remote_user [$time_local] "http://$host" "$request" '
  14.                           '$status $body_bytes_sent "$http_referer" "$http_user_agent" "$HTTP_X_UP_CALLING_LINE_ID" ';
  15. oo
复制代码





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2