插件窝 干货文章 Nginx服务器的日志分析和监控手段详细介绍

Nginx服务器的日志分析和监控手段详细介绍

Nginx log 日志 access 959    来源:    2025-04-12

Nginx服务器日志分析与监控全面指南

一、Nginx日志基础配置

1. 日志文件位置

Nginx默认日志通常位于: - 访问日志:/var/log/nginx/access.log - 错误日志:/var/log/nginx/error.log

2. 日志格式配置

在nginx.conf中可自定义日志格式:

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

3. 常用日志变量

  • $remote_addr: 客户端IP
  • $time_local: 本地时间
  • $request: 请求方法和URI
  • $status: HTTP状态码
  • $body_bytes_sent: 发送给客户端的字节数
  • $http_referer: 来源页面
  • $http_user_agent: 用户代理(浏览器信息)

二、日志分析工具

1. 基础命令行工具

awk简单分析

# 统计HTTP状态码
awk '{print $9}' access.log | sort | uniq -c | sort -rn

# 统计访问量前10的IP
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -n 10

grep过滤分析

# 查找404错误
grep ' 404 ' access.log

# 查找特定IP的访问
grep '192.168.1.100' access.log

2. GoAccess - 实时日志分析工具

# 安装
sudo apt-get install goaccess

# 基本使用
goaccess /var/log/nginx/access.log -a

# 生成HTML报告
goaccess /var/log/nginx/access.log -o report.html --log-format=COMBINED

3. ELK Stack (Elasticsearch, Logstash, Kibana)

完整日志分析解决方案: 1. Logstash配置示例:

input {
  file {
    path => "/var/log/nginx/access.log"
    start_position => "beginning"
  }
}

filter {
  grok {
    match => { "message" => "%{COMBINEDAPACHELOG}" }
  }
  date {
    match => [ "timestamp", "dd/MMM/yyyy:HH:mm:ss Z" ]
  }
}

output {
  elasticsearch {
    hosts => ["localhost:9200"]
  }
}
  1. Kibana提供可视化界面分析

4. Grafana + Prometheus + Loki

现代监控方案: - Prometheus: 收集指标 - Loki: 日志聚合 - Grafana: 可视化展示

三、实时监控方案

1. Nginx状态模块

启用内置状态监控:

server {
    listen 8080;
    server_name localhost;

    location /nginx_status {
        stub_status on;
        access_log off;
        allow 127.0.0.1;
        deny all;
    }
}

输出示例:

Active connections: 291 
server accepts handled requests
 16630948 16630948 31070465 
Reading: 6 Writing: 179 Waiting: 106 

2. Prometheus监控

使用nginx-exporter暴露指标:

# docker-compose示例
version: '3'
services:
  nginx-exporter:
    image: nginx/nginx-prometheus-exporter
    ports:
      - "9113:9113"
    command:
      - '-nginx.scrape-uri=http://nginx:8080/nginx_status'

3. 商业监控服务

  • Datadog
  • New Relic
  • Sumo Logic

四、安全分析与异常检测

1. 常见安全分析场景

# 检测扫描行为
grep -i 'scan|nmap|nikto|wpscan' access.log

# 检测SQL注入尝试
grep -i 'select.*from|union.*select|1=1' access.log

# 检测暴力破解
awk '{print $1,$7}' access.log | grep 'wp-login.php' | sort | uniq -c | sort -rn

2. Fail2Ban自动防护

配置示例:

[nginx-http-auth]
enabled = true
filter = nginx-http-auth
port = http,https
logpath = /var/log/nginx/error.log

[nginx-badbots]
enabled = true
port = http,https
filter = nginx-badbots
logpath = /var/log/nginx/access.log
maxretry = 2

五、日志轮转与管理

1. 使用logrotate

配置示例(/etc/logrotate.d/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
}

2. 日志清理策略

# 查找并删除超过30天的日志
find /var/log/nginx -name "*.log" -type f -mtime +30 -delete

六、高级分析与机器学习

1. 使用Python进行日志分析

import pandas as pd

df = pd.read_csv(
    'access.log', 
    sep=' ', 
    header=None, 
    names=['ip', 'ident', 'user', 'time', 'tz', 'request', 
           'status', 'size', 'referer', 'user_agent']
)

# 分析状态码分布
print(df['status'].value_counts())

# 分析热门请求
print(df['request'].value_counts().head(10))

2. 异常检测算法

  • 孤立森林(Isolation Forest)
  • 聚类分析(K-means)
  • 时间序列异常检测(Facebook Prophet)

七、最佳实践建议

  1. 结构化日志:使用JSON格式便于解析

    log_format json_combined escape=json
     '{'
       '"time_local":"$time_local",'
       '"remote_addr":"$remote_addr",'
       '"request":"$request",'
       '"status": "$status",'
       '"body_bytes_sent":"$body_bytes_sent",'
       '"http_referer":"$http_referer",'
       '"http_user_agent":"$http_user_agent"'
     '}';
    
  2. 分离日志:为不同虚拟主机配置独立日志文件

  3. 监控关键指标

    • 请求率(Request rate)
    • 错误率(Error rate)
    • 响应时间(Response time)
    • 带宽使用(Bandwidth usage)
  4. 设置告警:对异常模式(如大量5xx错误)设置自动告警

  5. 长期归档:重要日志压缩后存储到对象存储(S3等)

通过以上全面的日志分析和监控手段,您可以有效掌握Nginx服务器的运行状况,及时发现并解决问题,优化性能并增强安全性。