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