插件窝 干货文章 nginx的access_log日志怎么设置

nginx的access_log日志怎么设置

Nginx Access Log 日志 701    来源:    2025-04-21

Nginx Access Log 配置指南

access_log 是 Nginx 记录客户端请求的重要日志文件,以下是详细的配置方法:

基本配置语法

access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];

或关闭日志记录:

access_log off;

常用配置示例

1. 基本访问日志配置

http {
    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;
}

2. 不同虚拟主机使用不同日志文件

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

    location / {
        # 配置内容
    }
}

3. 条件日志记录

# 只记录状态码为4xx和5xx的请求
map $status $loggable {
    ~^[23]  0;
    default 1;
}

access_log /var/log/nginx/access.log main if=$loggable;

4. 缓冲日志写入

access_log /var/log/nginx/access.log main buffer=32k flush=5m;

5. 日志轮转和压缩

access_log /var/log/nginx/access.log main gzip=1;

常用日志变量

变量 描述
$remote_addr 客户端IP地址
$remote_user 客户端用户名(基本认证)
$time_local 本地时间
$request 完整的请求行
$status 响应状态码
$body_bytes_sent 发送给客户端的字节数
$http_referer 请求来源页
$http_user_agent 客户端浏览器信息
$http_x_forwarded_for 代理服务器IP链

高级配置

1. JSON格式日志

log_format json_combined escape=json
    '{'
        '"time_local":"$time_local",'
        '"remote_addr":"$remote_addr",'
        '"remote_user":"$remote_user",'
        '"request":"$request",'
        '"status": "$status",'
        '"body_bytes_sent":"$body_bytes_sent",'
        '"http_referer":"$http_referer",'
        '"http_user_agent":"$http_user_agent",'
        '"http_x_forwarded_for":"$http_x_forwarded_for"'
    '}';

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

2. 按日期分割日志

map $time_iso8601 $logdate {
    '~^(?<ymd>\d{4}-\d{2}-\d{2})' $ymd;
    default 'date-not-found';
}

access_log /var/log/nginx/access-$logdate.log main;

日志轮转

建议使用 logrotate 管理 Nginx 日志轮转:

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

性能优化建议

  1. 对于高流量网站,考虑使用缓冲日志写入
  2. 可以关闭静态资源访问日志
  3. 定期检查日志文件大小并轮转
  4. 考虑将日志写入内存文件系统提高性能

希望这些配置示例对您有所帮助!如需更具体的配置,请提供您的具体需求。