Nginx的日志分兩種:錯誤日志(error log)、訪問日志(access log)缰雇,一般存放在nginx安裝目錄下logs目錄里疯特,默認(rèn)分別為“error.log“、“access.log”
錯誤日志 記錄網(wǎng)絡(luò)發(fā)生異常錯誤時的信息蔼囊,方便發(fā)生錯誤時對問題進(jìn)行追蹤焚志,訪問日志 則記錄所有對服務(wù)的訪問信息,可對用戶的瀏覽行為進(jìn)行追蹤
訪問日志
nginx的訪問日志主要有以下2個參數(shù)控制
- log_format:
用來定義記錄日志的格式(可以定義多種日志格式畏鼓,取不同的名字即可) - access_log:
用來指定日志文件的路徑及使用何種日志格式記錄日志
日志格式
日志格式 log_format 語法如下
log_format name [escape=default|json|none] string ...;
// default value
log_format combined '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
name: 為日志格式命名酱酬,可定義多個日志格式
string: 具體格式
escape: none 對字符不轉(zhuǎn)義,json|default則對字符進(jìn)行轉(zhuǎn)義
部分可用字段
字段名 | 描述 |
---|---|
$remote_addr | 記錄訪問網(wǎng)站的客戶端地址云矫; |
$http_x_forwarded_for | 當(dāng)前端有代理服務(wù)器時膳沽,設(shè)置web節(jié)點記錄客戶端地址的配置,此參數(shù)生效的前提是代理服務(wù)器上也進(jìn)行了相關(guān)的x_forwarded_for設(shè)置让禀; |
$remote_user | 遠(yuǎn)程客戶端用戶名稱挑社; |
$time_local | 記錄訪問時間與時區(qū); |
$request | 用戶的http請求起始行信息巡揍; |
$status | http狀態(tài)碼痛阻,記錄請求返回的狀態(tài),例如200腮敌、404阱当、301等; |
$body_bytes_sent | 服務(wù)器發(fā)給客戶端的響應(yīng)body字節(jié)數(shù)糜工; |
$http_referer | 記錄此次請求是從哪個鏈接訪問呢過來的弊添,可以根據(jù)referer進(jìn)行防盜鏈設(shè)置; |
$http_user_agent | 記錄客戶端訪問信息啤斗,例如:瀏覽器表箭、手機(jī)客戶端等; |
存放位置: http
日志文件
定義日志文件語法如下
access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
access_log off
// default value
access_log logs/access.log combined;
path: 存放路徑钮莲, 默認(rèn)為logs/access.log
format: 日志格式,默認(rèn)為combine
buffer=size: 存放日志的緩沖區(qū)大小
flush=time: 為將緩沖區(qū)的日志刷到磁盤的時間
gzip[=level] : 表示壓縮級別
[if=condition] : 表示其他條件彼水,一般場景這些參數(shù)都無需配置崔拥,極端優(yōu)化時才可能考慮這些參數(shù)。
放置位置:http, server, location, if in location, limit_except中
實例
以下示例定義了兩個日志格式main凤覆,json链瓦,定義默認(rèn)的日志路徑logs/access.log, 并在8080端口的server中自定義日志文件盯桦。
[root@nginx conf]# cat nginx.conf
worker_processes 1;
error_log logs/error.log error;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
log_format json '{ address: $remote_addr }';
access_log logs/access.log main; // 默認(rèn)日志文件
sendfile on;
keepalive_timeout 65;
server {
listen 8080慈俯;
access_log /data/project/logs/report.log json; // 自定義日志文件
root /data/project;
}
}
參考文章
https://www.cnblogs.com/Mr-Ding/p/9539867.html
http://www.madblog.cn/posts/e4dd5bbae50fa621.html