nginx - 截斷訪問日誌中的字段

nginx - 截斷訪問日誌中的字段

有沒有辦法截斷儲存在存取日誌中的欄位內容?

我有興趣只保留用戶代理的前十個字元。

答案1

首先,您引入一個包含截斷的用戶代理程式的自訂變數。為此,您可以map在常規使用者代理變數 上使用指令$http_user_agent。地圖模組的文檔在這裡:http://nginx.org/en/docs/http/ngx_http_map_module.html。然後使用log_format指令配置日誌記錄格式,請參閱文檔https://docs.nginx.com/nginx/admin-guide/monitoring/logging/。最後,您告訴access_log使用您的自訂日誌記錄格式。

總之:

# ...
http {
    map $http_user_agent $trunc_agent {
        default "";
        "~*(?P<tr>.{0,10}).*" $tr;
    }
    log_format myformat '[other fields] "$trunc_agent"';
    access_log [logfile] myformat;
}
# ...

相關內容