Nginx日志格式可以通過修改Nginx配置文件來自定義。以下是如何自定義配置Nginx日志格式的步驟:
打開Nginx配置文件。通常位于/etc/nginx/nginx.conf或/etc/nginx/sites-available/your_domain.conf。
在http塊或server塊中,使用log_format指令定義自定義日志格式。例如,創建一個名為custom_log_format的自定義日志格式:
http {
...
log_format custom_log_format '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$http_x_forwarded_for" "$request_time"';
...
}
在這個例子中,我們定義了一個包含以下字段的自定義日志格式:
$remote_addr:客戶端IP地址$remote_user:遠程用戶名(如果已認證)$time_local:本地時間格式的日期和時間$request:請求行,包括HTTP方法、URL和HTTP版本$status:響應狀態碼$body_bytes_sent:發送給客戶端的響應體字節數$http_referer:引用頁面的URL$http_user_agent:客戶端瀏覽器信息$http_x_forwarded_for:X-Forwarded-For頭部的值,用于記錄代理服務器的IP地址$request_time:處理請求所花費的時間server塊中,使用access_log指令引用自定義日志格式。例如,將自定義日志格式應用于名為your_domain.conf的配置文件中的access_log指令:server {
...
access_log /var/log/nginx/your_domain_access.log custom_log_format;
...
}
sudo nginx -t # 檢查配置文件語法是否正確
sudo nginx -s reload # 重新加載配置文件
現在,Nginx將使用自定義日志格式記錄訪問日志。請注意,根據您的需求,您可以根據需要添加或刪除字段。