日志指令
- Nginx服务器中常用access_log、error_log配置日志指令,用于定义不同日志的写入路径和格式。
- 日志指令在 Nginx 中可以配置在不同的作用域,每个作用域的优先级和影响范围不同
error_log /var/log/nginx/error.log warn;
http {
error_log /var/log/nginx/http_error.log info;
server {
# ...
}
}
http {
error_log /var/log/nginx/http_error.log info;
server {
listen 80;
server_name localhost;
error_log /var/log/nginx/example_error.log notice;
location / {
# ...
}
}
}
-
- location{...},location作用域
http {
server {
listen 80;
server_name localhost;
error_log /var/log/nginx/example_error.log notice;
location / {
root /usr/share/nginx/html;
error_log /var/log/nginx/location_error.log debug;
}
location /api/ {
proxy_pass http://backend;
error_log /var/log/nginx/api_error.log info;
}
}
}
配置示例
定义格式
- 使用log_format指令命名一个日志格式
- access:命名一个日志格式变量名称,可在access_log指令中引用,例如:access_log /usr/local/nginx/logs/access.log access;
- $xxx:获取变量的内容,如:$request_body,获取客户端请求的Body内容。
http{
log_format access '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $http_x_forwarded_for $request_body '
'"$upstream_cache_status" $upstream_status '
'【"$request_time"s - "$upstream_response_time"s - $upstream_addr】';
}
设置格式
server {
listen 29020;
server_name localhost;
# 设置日志位置
access_log logs/29020.access.log access;
error_log logs/29020.error.log;
location / {
# ...
}
}
查看日志输出
192.168.1.81 - - [17/Sep/2025:22:05:15 +0800] "GET /querey/contentType/list?publishOrgId=1705097481613915421 HTTP/1.1" 200 13955 "http://192.168.6.12:29020/welcome/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36" - - "-" 200 【"0.012"s - "0.012"s - 192.168.6.13:9090】