要自定義 Nginx 日志輸出,您需要編輯 Nginx 配置文件(通常位于 /etc/nginx/nginx.conf 或 /etc/nginx/sites-available/ 目錄下的某個文件)。以下是一些步驟和示例,幫助您自定義 Nginx 日志輸出。
sudo nano /etc/nginx/nginx.conf
或者,如果您知道特定站點的配置文件,可以編輯該文件:
sudo nano /etc/nginx/sites-available/your-site.conf
在 http
、server
或 location
塊中,找到 access_log
和 error_log
指令。如果沒有找到這些指令,請將它們添加到適當的塊中。
自定義日志格式。在 http
、server
或 location
塊中,使用 log_format
指令定義一個新的日志格式。例如,以下是一個名為 custom_format
的自定義日志格式:
log_format custom_format '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$http_x_forwarded_for" "$request_time"';
這個自定義格式包括遠程地址、遠程用戶、本地時間、請求、狀態碼、發送的字節數、引用頁、用戶代理、轉發請求的 IP 地址和請求時間。
access_log
指令。在 server
或 location
塊中,將 access_log
指令的值更改為您剛剛創建的自定義格式。例如:access_log /var/log/nginx/access.log custom_format;
這將使 Nginx 使用 custom_format
格式記錄訪問日志。
error_log
指令和 log_format
指令創建一個新的錯誤日志格式。例如:error_log /var/log/nginx/error.log custom_error_format debug;
將 custom_error_format
替換為您選擇的錯誤日志格式名稱。
保存更改并退出編輯器。
檢查 Nginx 配置文件的語法是否正確:
sudo nginx -t
如果配置文件語法正確,您將看到以下輸出:
nginx: configuration file /etc/nginx/nginx.conf test is successful
sudo systemctl reload nginx
現在,Nginx 將使用您自定義的日志格式輸出訪問和錯誤日志。請注意,更改日志格式可能會影響日志文件的可讀性,因此請確保您選擇的字段對您的需求有幫助。