使用log_format为Nginx服务器设置更详细的日志格式方法

  

使用log_format为Nginx服务器设置更详细的日志格式可以帮助我们更好地监控和分析访问日志。下面是设置更详细的日志格式的完整攻略:

步骤一:备份Nginx配置文件

在进行任何更改之前,请确保备份您的Nginx配置文件。以Ubuntu 18.04为例,可以使用以下命令备份配置文件:

sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak

步骤二:打开Nginx配置文件

使用文本编辑器打开Nginx配置文件,例如在Ubuntu 18.04中,可以使用如下命令打开Nginx配置文件:

sudo nano /etc/nginx/nginx.conf

步骤三:配置log_format

在http块中,使用log_format设置更详细的日志格式,例如:

http {
    log_format  acc_combined  '$remote_addr - $remote_user [$time_local] "$request" '
                            '$status $body_bytes_sent "$http_referer" '
                            '"$http_user_agent" "$http_x_forwarded_for"';
}

上面的log_format将在访问日志中包含远程IP地址,远程用户身份,访问时间,请求URI,HTTP响应状态码,响应体大小,Referer,User-Agent和X-Forwarded-For等信息。

步骤四:启用log_format

在server块中使用access_log指令启用log_format,例如:

server {
    listen 80;
    server_name example.com;
    access_log /var/log/nginx/access.log acc_combined;
    ...
}

上述access_log指令中的acc_combined对应的就是上面所定义的log_format。当然,如果不想使用自定义的log_format,可以直接使用预设的响应式Access Log,例如:

access_log /var/log/nginx/access.log;

步骤五:重新加载Nginx配置文件

保存Nginx配置文件后,使用以下命令重新加载配置文件:

sudo systemctl reload nginx

设置完成后,每当有客户端访问服务器时,做出的响应都将被记录到Nginx日志文件中,该日志文件的位置为上述设置access_log指令中的文件路径。

示例一:nginx.conf配置文件中的log_format设置

http {
    ##日志格式化 
    log_format  webservers  '$remote_addr $remote_user [$time_local] "$request" '
                         '$status $body_bytes_sent "$http_referer" '
                         '"$http_user_agent" $gzip_ratio $request_time';
}

示例二:server块配置文件中的access_log指令

server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;
        #access_log  /var/log/nginx/host.access.log  main;

        ##将web1日志单独写入一个文件 
        access_log /data/logs/nginx/access.log webservers;

        location /nginx_status {
          vhost_traffic_status_display;
          vhost_traffic_status_display_format html;
        }
        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
        }
        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/share/nginx/html;
        }
}

以上两个示例来自Nginx官网,第一个示例是在http块中设置log_format,第二个示例在server块中使用access_log指令启用log_format。其中示例一中的log_format名称为webservers,涵盖了请求客户端IP地址,远程用户身份,访问时间,请求的URI,HTTP响应状态码,响应体大小,Referer,User-Agent,压缩比率和请求处理时间等信息。示例二中使用access_log指令将log_format记录到了access.log文件中。在这个例子中,使用的log_format是webservers,与示例一中的log_format名称保持一致。

相关文章