溫馨提示×

如何自定義nginx日志字段

小樊
130
2025-02-13 22:18:03
欄目: 編程語言

要自定義 Nginx 日志字段,您需要修改 Nginx 配置文件中的 log_format 指令。以下是自定義日志字段的步驟:

  1. 打開 Nginx 配置文件。通常位于 /etc/nginx/nginx.conf/etc/nginx/sites-available/your_domain.conf。

  2. http 塊中,找到或創建一個 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" '
                                  '"$custom_field1" "$custom_field2"';
    # ...
}

在這個例子中,我們添加了兩個自定義字段:$custom_field1$custom_field2。您可以根據需要添加更多字段。

  1. serverlocation 塊中,使用 access_log 指令引用您剛剛創建的自定義日志格式。例如:
server {
    # ...
    access_log /var/log/nginx/your_domain.access.log custom_log_format;
    # ...
}

這將使 Nginx 使用您定義的 custom_log_format 記錄訪問日志。

  1. 如果您還想要在錯誤日志中包含自定義字段,可以在 http 塊中使用 error_log 指令,并引用相同的自定義日志格式:
http {
    # ...
    error_log /var/log/nginx/your_domain.error.log custom_log_format debug;
    # ...
}
  1. 保存更改并重新加載 Nginx 配置以使更改生效:
sudo nginx -t      # 檢查配置文件語法是否正確
sudo nginx -s reload  # 重新加載配置文件

現在,Nginx 日志將包含您定義的自定義字段。請注意,自定義字段不會自動填充任何值,因此您可能需要使用第三方模塊(如 ngx_http_realip_module 或 ngx_http_sub_module)或在應用程序中設置這些值。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女