未雨绸缪,考虑到以后可能服务器增多,如果日志不集中管理,单台日志查看,还是显得比较麻烦。
有常查看nginx日志的需求,所以,打算利用rsyslog对nginx日志做个集中管理。
这里假设日志中心为center,节点1为node1
| 服务器 | IP | 
| Center | 192.168.1.2 | 
| Node1 | 192.168.1.3 | 
配置都是基于Centos7 默认的rsyslog版本 7.4.7  V5、V7、V8配置差别似乎挺大的,所以尽量用同样的版本吧
Center配置
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 
 | # vim /etc/rsyslog.conf# 开启端口给node传送数据。这里吧tcp和udp端口都打开了
 # 配置前面加了$的都代表是全局配置
 $ModLoad imudp
 $UDPServerRun 514
 $ModLoad imtcp
 $InputTCPServerRun 514
 # 允许特定IP段才能连接端口
 $AllowedSender tcp, 192.168.1.0/24
 # 新建一个模板
 $template Remote,"/data/log/%fromhost-ip%/%fromhost-ip%_%$YEAR%-%$MONTH%-%$DAY%.log"
 # 过滤本地消息
 :fromhost-ip, !isequal, "127.0.0.1" ?Remote
 
 
 | 
配置好rsyslog,就可以重启一下服务了。
#systemctl restart rsyslog
如果没意外,netstat  -antp | grep rsyslog 就能看到开放的514端口了。
Node1配置
| 12
 3
 4
 
 | ## 将所有等于或者大于info级别的信息传到Center*.info;mail.none;authpriv.none;cron.none                @@192.168.1.2
 $template myFormat,"%timestamp% %fromhost-ip%%msg%\n"
 
 
 | 
重启服务systemctl restart rsyslog,这个时候用logger "test"
在Center的/var/log/messages日志应该就能看到了。
配置nginx日志传输 同理也可以用到其它日志传输上。
新版本的nginx基本都支持在nginx配置中,直接配置syslog。
但是我这里还是用老办法。现在rsyslog配置读取nginx的日志文件,然后传送过去,这个办法也试用于其它服务的日志。
Node1 新建一个rsyslog配置nginx.conf 
| 12
 3
 4
 5
 6
 7
 8
 
 | vim /etc/rsyslog.d/nginx.conf# 关键是路径和tag、statefile
 module(load="imfile" PollingInterval="5")
 $InputFileName /var/log/nginx/access.log
 $InputFileTag nginx-access-1:
 $InputFileStateFile state-nginx-access-1
 $InputRunFileMonitor
 
 
 | 
我在一台V5版本上是这样配的
| 12
 3
 4
 5
 6
 7
 8
 
 | $ModLoad imfile$InputFileName /var/log/nginx/access.log
 $InputFileTag nginx-access-1:
 $InputFileStateFile state-nginx-access-1
 $InputFileFacility local5
 $InputFileSeverity info
 $InputRunFileMonitor
 
 
 | 
Center
这个配置例子好匮乏,找了好多资料,终于谷爹那里找到了。见文末参考资料。根据配置的tag导出日志到特定文件。
同样新建一个rsyslog配置文件nginx.conf,使用omfile模块,用dynaFile参数实现动态文件名。这个很多国内文章基本都没提到,还是看帮助文档发现这个的。否则我就用logrotate了。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 
 | vim /etc/rsyslog.d/nginx.conftemplate(name="OnlyMsg" type="string" string="%msg:2:$%\n")
 template(name="dynaname" type="string" string="/logfiles/%fromhost-ip%/access-%$YEAR%%$MONTH%%$DAY%.log")
 if( $syslogtag == 'nginx-access-1:')  then {
 # write to file
 action(type="omfile" dynaFile="dynaname" template="OnlyMsg")
 # forward over network
 call sendToLogserver
 stop
 }
 
 
 | 
重启rsyslog,应该就没问题了。
参考资料
      