Nginx的日志格式主要包括访问日志(access log)和错误日志(error log),它们记录了服务器运行时的各种信息,帮助管理员监控和优化服务器运行情况。
访问日志记录了客户端访问请求的详细信息,通常包括以下字段:
remote_addr
: 客户端IP地址。remote_user
: 客户端用户名称(如果通过认证)。time_local
: 访问时间及时区。request
: 请求的URL与HTTP协议。status
: HTTP请求状态码。body_bytes_sent
: 发送给客户端的字节数。http_referer
: 访问来源的页面链接地址。http_user_agent
: 客户端浏览器的相关信息。http_x_forwarded_for
: 在经过多个代理时,记录最终客户端的IP地址。访问日志的默认格式是 main
,可以在 nginx.conf
文件中通过 log_format
指令进行自定义。例如:
log_format main '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" "$http_x_forwarded_for"';
错误日志记录了Nginx服务器运行时出现的错误信息,例如配置错误、服务器错误等。错误日志的格式通常包括以下字段:
error_message
: 错误的具体信息。error_time
: 错误发生的时间。错误日志的默认格式是 error
,也可以在配置文件中自定义。例如:
error_log /var/log/nginx/error.log error;
除了默认的 main
格式,Nginx允许用户自定义日志格式以满足特定需求。例如,可以记录请求的长度、请求时间等信息:
log_format custom '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' "$http_referer" "$http_user_agent" $request_length $request_time';
然后通过 access_log
指令使用自定义格式:
access_log /var/log/nginx/access.log custom;
通过这些配置,Nginx可以详细记录请求信息,帮助管理员进行故障排查和性能优化。