nginx 日志log_format格式
2018-10-05 23:12 youxin 阅读(3187) 评论(0) 编辑 收藏 举报官方文档:
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
中,我们定义了两种的日志格式:main
和log_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脚本分割。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
2013-10-05 单次遍历,带权随机选取问题
2013-10-05 转:面试中常见的一些算法问题
2013-10-05 树状数组资料
2013-10-05 逆序数的求法
2013-10-05 全排列的hash
2013-10-05 转:2个指针位置的妙用
2013-10-05 编程珠玑I算法总结