温馨提示×

nginx日志怎么配置格式

小樊
46
2026-09-29 19:20:58
栏目: 编程语言

在 Nginx 中,日志格式是通过 log_format 指令来定义的,然后在 access_log 指令中引用该格式。

下面给你一个从基础到常用的完整说明。


一、基本配置位置

日志格式一般配置在 http 块中(全局生效):

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

    access_log  /var/log/nginx/access.log  main;
}
  • log_format:定义日志格式
  • main:格式名称(可自定义)
  • access_log:指定日志文件和使用的格式

二、常用内置变量说明

变量 含义
$remote_addr 客户端 IP
$remote_user 认证用户(无则为 -)
$time_local 本地时间
$request 请求行(方法 + URL + 协议)
$status HTTP 状态码
$body_bytes_sent 发送给客户端的字节数
$http_referer 来源页面
$http_user_agent 客户端浏览器/代理
$request_time 请求总耗时(秒)
$upstream_response_time 后端响应时间

三、常见日志格式示例

1️⃣ 默认格式(Nginx 自带)

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

2️⃣ 包含响应时间的格式(推荐)

log_format  json  escape=json  '{'
    '"time":"$time_local",'
    '"remote_addr":"$remote_addr",'
    '"request":"$request",'
    '"status":$status,'
    '"request_time":$request_time,'
    '"upstream_time":"$upstream_response_time",'
    '"ua":"$http_user_agent"'
'}';

使用:

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

✅ 适合 ELK / Loki / 日志采集


3️⃣ 多格式分别记录

http {
    log_format  main  '...';
    log_format  debug '...';

    server {
        access_log  /var/log/nginx/access.log  main;
        access_log  /var/log/nginx/debug.log  debug;
    }
}

四、错误日志配置

错误日志不在 log_format 控制范围内:

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

日志级别:

debug < info < notice < warn < error < crit < alert < emerg

五、按 server / location 配置

server {
    listen 80;
    server_name example.com;

    access_log  /var/log/nginx/example.log  main;

    location /api/ {
        access_log  /var/log/nginx/api.log  json;
    }
}

六、关闭访问日志

access_log off;

如果你有具体需求(比如 JSON 格式 / 统计 PV / 接入日志系统 / 性能分析),可以告诉我,我可以直接给你一份可用配置。

0 踩