1. 程式人生 > 實用技巧 >nginx日誌輸出配置json格式

nginx日誌輸出配置json格式

修改nginx配置檔案

http {
    include       mime.types;
    default_type  application/octet-stream;
    charset  utf-8;
    
    # 原有日誌格式
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" $request_time';
    # json日誌格式
    log_format log_json '{"@timestamp": "$time_local", '
                        '"remote_addr": "$remote_addr", '
                        '"referer": "$http_referer", '
                        '"request": "$request", '
                        '"status": $status, '
                        '"bytes": $body_bytes_sent, '
                        '"agent": "$http_user_agent", '
                        '"x_forwarded": "$http_x_forwarded_for", '
                        '"up_addr": "$upstream_addr",'
                        '"up_host": "$upstream_http_host",'
                        '"up_resp_time": "$upstream_response_time",'
                        '"request_time": "$request_time"'
                        ' }';

    access_log  logs/access.log log_json; # 引用日誌格式名稱

    (省略內容)
}

在 Nginx 的配置檔案nginx.conf中,我們定義了兩種的日誌格式:main和log_json,其中,main為普通的文字格式,log_json為 json 格式。log_json其實就是手工構造一個 json 字串。定義了 json 的日誌格式後,便可以指定 access log 為 json 格式.
修改 Nginx 的配置,重啟 Nginx ,便可以看到 json 格式的日誌,重啟 Nginx:

擴充套件:log_format指令中常用的一些變數
地址:https://www.cnblogs.com/sanduzxcvbnm/p/14250758.html