当前位置: 代码网 > 服务器>服务器>Linux > Nginx中打印请求日志的完整指南

Nginx中打印请求日志的完整指南

2026年09月08日 Linux 我要评论
前言nginx作为代理时,可以配置打印请求日志,便于定位问题nginx打印请求日志可以使用配置 # 打印请求方式和 url 的日志格式 log_format req_format '$re

前言

nginx作为代理时,可以配置打印请求日志,便于定位问题

nginx打印请求日志

可以使用配置

    # 打印请求方式和 url 的日志格式
    log_format req_format '$remote_addr [$time_local] method=$request_method url=$request_uri';

打印nginx日志信息

#user  nobody;
worker_processes  1;
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#pid        logs/nginx.pid;
events {
    worker_connections  1024;
}
http {
    include       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  logs/access.log  main;
    # 打印请求方式和 url 的日志格式
    log_format req_format '$remote_addr [$time_local] method=$request_method url=$request_uri';
    sendfile        on;
    #tcp_nopush     on;
    #keepalive_timeout  0;
    keepalive_timeout  65;
    #gzip  on;
    server {
        listen       80;
        server_name  localhost;
        access_log  d:/temp/access.log  req_format;
        location / {
            root   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   html;
        }
        # proxy the php scripts to apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}
        # pass the php scripts to fastcgi server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  script_filename  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}
        # deny access to .htaccess files, if apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }
    # another virtual host using mix of ip-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
    # https server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;
    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;
    #    ssl_session_cache    shared:ssl:1m;
    #    ssl_session_timeout  5m;
    #    ssl_ciphers  high:!anull:!md5;
    #    ssl_prefer_server_ciphers  on;
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
}

知识扩展

nginx 日志打印完整指南

nginx 提供了两种核心日志:访问日志(access log) 和错误日志(error log)

正确配置和查看它们,是排查问题、分析流量、监控安全的基础。

访问日志(access log)

访问日志记录每次客户端请求的详细信息,如 ip、请求时间、方法、uri、状态码、响应大小等。

1. 启用访问日志

在 httpserver 或 location 块中使用 access_log 指令:

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

可以指定日志文件路径,也可以输出到 syslog:

access_log syslog:server=unix:/dev/log,tag=nginx;

2. 自定义日志格式(log_format)

nginx 允许定义多种格式,通过 log_format 指令:

http {
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
    
    log_format json escape=json '{"time":"$time_iso8601",'
                                '"remote_addr":"$remote_addr",'
                                '"request":"$request",'
                                '"status":$status,'
                                '"body_bytes_sent":$body_bytes_sent,'
                                '"referer":"$http_referer",'
                                '"user_agent":"$http_user_agent"}';
    
    access_log /var/log/nginx/access.log main;
    access_log /var/log/nginx/access.json.log json;
}

常用内置变量

变量含义
$remote_addr客户端 ip
$remote_user基本认证用户名
$time_local本地时间
$request请求方法+uri+协议
$status响应状态码
$body_bytes_sent响应体大小(不含头部)
$http_referer来源页面
$http_user_agent客户端浏览器信息
$http_x_forwarded_for代理链中的真实 ip
$request_time请求处理耗时(秒)
$upstream_response_time上游服务器响应时间

3. 关闭或条件性日志

# 关闭特定 location 的访问日志
location /health {
    access_log off;
}

# 根据状态码决定是否记录(使用 if)
map $status $loggable {
    default 1;
    404 0;
}
access_log /var/log/nginx/access.log main if=$loggable;

错误日志(error log)

错误日志记录 nginx 自身运行错误、配置问题、后端连接失败等。

1. 基本配置

error_log /var/log/nginx/error.log warn;

日志级别(从低到高):debuginfonoticewarnerrorcritalertemerg

生产环境常用 warn 或 error,调试时临时设为 debug

2. 调试模式(打印更详细日志)

编译 nginx 时需添加 --with-debug,然后在配置中启用:

error_log /var/log/nginx/error.log debug;

这会记录每个请求的完整处理过程,仅用于临时调试,避免长期开启

日志切割与轮转(log rotation)

nginx 本身不切割日志,通常配合 logrotate 工具。

创建 /etc/logrotate.d/nginx

/var/log/nginx/*.log {
    daily
    missingok
    rotate 30
    compress
    delaycompress
    notifempty
    create 0640 nginx adm
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -usr1 `cat /var/run/nginx.pid`
    endscript
}

kill -usr1 会通知 nginx 重新打开日志文件,实现无缝切割。

实时查看与过滤日志

# 实时查看访问日志
tail -f /var/log/nginx/access.log

# 过滤特定状态码
tail -f /var/log/nginx/access.log | grep '" 500 '

# 查看错误日志并高亮
tail -f /var/log/nginx/error.log | grep -i error

# 查看最近100条访问日志
tail -n 100 /var/log/nginx/access.log

# 统计 ip 访问次数
awk '{print $1}' access.log | sort | uniq -c | sort -nr | head -10

将日志输出到标准输出(适用于容器环境)

在 docker/kubernetes 中,通常希望 nginx 将日志输出到 stdout / stderr,以便日志系统收集:

access_log /dev/stdout main;
error_log /dev/stderr warn;

或在 nginx.conf 中这样配置(推荐):

daemon off;
error_log /dev/stderr info;
http {
    access_log /dev/stdout main;
    ...
}

调试技巧:打印请求变量

有时需临时查看某个请求的特定变量,可以用 error_log 结合 return 或 echo 模块(需编译):

location /debug {
    access_log /var/log/nginx/debug.log main;
    return 200 "remote_addr: $remote_addr\nhost: $host\n";
}

或使用 add_header 将变量写入响应头(仅供开发测试):

add_header x-debug-ip $remote_addr always;

总结

nginx打印请求日志,有时候便于线上定位问题

到此这篇关于nginx中打印请求日志的完整指南的文章就介绍到这了,更多相关nginx打印请求日志内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com