6. Nginx基础模块-Nginx日志配置

1 Nginx日志配置

ELK

	Nginx	Java	json
192.168.104.143 - - [20/Jan/2020:13:58:02 +0800] "GET /%E8%85%BE%E8%AE%AF%E9%A6%96%E9%A1%B5_files/default_b.png HTTP/1.1" 200 10392 "http://192.168.101.82/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36" "-"

Nginx有非常灵活的日志记录模式,每个级别的配置可以有各自独立的访问日志,日志格式 通过log_format命令自定义格式。

1.1 log_format指令

#配置语法:包括: error.log access.log

Syntax: log_format name [escape=default | json ] string …;

Default: log_format combined “…”;

Context: http

1.2 默认nginx定义语法

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

nginx日志格式允许包含的变量

  • $remote_addr 记录客户端IP地址
  • $remote_user 记录客户端用户名
  • $time_local 记录通用本地时间
  • $time_iso8601 记录ISO8601标准格式下的本地时间
  • $request 记录请求的方法以及请求的http协议
  • $status 记录请求的状态码(用户定位错误信息)
  • $body_bytes_sent 发送给客户端的总字节数,不包含响应头的大小
  • $bytes_sent 发送给客户端的总字节数
  • $msec 日志写入时间,单位为秒,精度是毫秒
  • $http_referer 记录从那个页面链接访问过来的
  • $http_user_agent 记录客户端浏览器相关信息
  • $http_x_forwarded_for 记录客户端ip地址
  • $request_length 请求的长度
  • $request_time 请求花费的时间,单位为秒,精度毫秒

注意:

如果Nginx位于负载均衡器,nginx反向代理后,web服务器无法直接获取客户端真是ip地址。

$remote_addr获取的是反向代理的ip地址。反向代理服务器在转发请求http头信息中

增加x+Forwarded_For信息,用来记录客户端ip地址和客户端请求的服务器地址

1.3 access_log使用方法

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;  
log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

# access_log  /var/log/nginx/access.log  main;
server {
        listen       80;
        server_name  localhost;
        access_log  logs/host.access.log  main;       //存放日志文件,并调用main日志格式
        location / {
            root   html;
            index  index.html index.htm;
        }
}

猜你喜欢

转载自blog.csdn.net/weixin_43357497/article/details/113764083