nginx 日志log_format格式


官方文檔:

http://nginx.org/en/docs/http/ngx_http_log_module.html

The ngx_http_log_module module writes request logs in the specified format.

Requests are logged in the context of a location where processing ends. It may be different from the original location, if an internal redirect happens during request processing.

Example Configuration

 

log_format compression '$remote_addr - $remote_user [$time_local] '
                       '"$request" $status $bytes_sent '
                       '"$http_referer" "$http_user_agent" "$gzip_ratio"';

access_log /spool/logs/nginx-access.log compression buffer=32k;

Nginx大致有三類變量能夠記錄在log_format 中

  • HTTP請求變量- arg_PARAMETER http_HEADER send_http_HEADER(服務端返回)
  • 內置變量- Nginx內置的
  • 自定義變量- 自己定義的

我們看一下默認的log_format

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; 

我們看到默認的格式,基本都是單引號 '' 包裹着一些變量,還包括 中划線 - 方括號 [] 作為分隔符一起打印。
每個變量都有這含義:

remote_addr:對應客戶端的地址
remote_user:是請求客戶端請求認證的用戶名,如果沒有開啟認證模塊的話是值為空。
time_local:表示nginx服務器時間
request:表示request請求頭的行
status:表示response的返回狀態
body_bytes_sent:表示從服務端返回給客戶端的body數據大小
http_referer:表示請求的上一級頁面
http_user_agent:表示agent信息
http_x_forwarded_for:會記錄每一級請求中信息

1、log_format 普通格式

1
2
3
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" "$upstream_response_time"' ;

2、log_format JSON 格式

為了便於利用 Elastic Stack 日志平台收集展示 Nginx 的日志,可以將 Nginx 的日志改成 json 的格式。修改后的 json 日志格式如下所示:

在 Nginx 的配置文件nginx.conf中,我們定義了兩種的日志格式:mainlog_json,其中,main為普通的文本格式,log_json為 json 格式。log_json其實就是手工構造一個 json 字符串。定義了 json 的日志格式后,便可以指定 access log 為 json 格式: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
log_format logJson '{
                          "@timestamp" "$time_local" , '
                          '"@fields": { '
                          '"remote_addr": "$remote_addr", '
                          '"remote_user": "$remote_user", '
                          '"body_bytes_sent": "$body_bytes_sent", '
                          '"request_time": "$request_time", '
                          '"status": "$status", '
                          '"request": "$request", '
                          '"request_method": "$request_method", '
                          '"http_referrer": "$http_referer", '
                          '"body_bytes_sent":"$body_bytes_sent", '
                          '"http_x_forwarded_for": "$http_x_forwarded_for", '
                          ' "http_user_agent" "$http_user_agent"  }
                          }';

nginx的log是沒有自動分割功能的。需要自己寫shell腳本分割


 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM