Caddy日志格式标准化
对Caddy2原生的富文本json日志文件,改为common_log
通用格式,使日志文件更易读,同时降低不同Web服务器日志格式的差异化程度。
引入
首先,我们先来看一下默认情况下可用的日志配置
example.com {
reverse_proxy * 127.0.0.1:8080
log {
output file /root/data/caddy/log/example.com/access.log {
roll_size 25MB
roll_keep 10
roll_keep_for 24h
}
}
}
在这个配置内,设置了站点日志输出目录,文件滚动大小和最长保留时间
入门
这个配置可以简单的把原生的富文本(不易阅读),转换为更为常用且易于阅读的common_log格式
example.com {
reverse_proxy * 127.0.0.1:8080
log {
format transform `{request>headers>X-Forwarded-For>[0]:request>remote_ip} - {user_id} [{ts}] "{request>method} {request>uri} {request>proto}" {status} {size} "{request>headers>Referer>[0]}" "{request>headers>User-Agent>[0]}"` {
time_format "02/Jan/2006:15:04:05 -0700"
}
output file /root/data/caddy/log/:8080/access.log {
roll_size 25MB
roll_keep 10
roll_keep_for 24h
}
}
}
输出内容示例:
192.168.2.98 - - [05/Apr/2024:15:07:34 +0000] "GET / HTTP/1.1" 200 3818 "http://192.168.2.31:8080/archives/hello-halo" "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Mobile Safari/537.36"
配置
这个功能需要插件实现,你可以通过add-package便捷安装,也可以使用xcaddy编译安装
- Add-Package
./caddy add-package github.com/caddyserver/transform-encoder
- XCaddy
xcaddy build \
--with github.com/caddyserver/transform-encoder
插件安装完毕后,在站点配置内添加日志配置即可
example.com {
reverse_proxy * 127.0.0.1:8080
log {
format transform `{request>headers>X-Forwarded-For>[0]:request>remote_ip} - {user_id} [{ts}] "{request>method} {request>uri} {request>proto}" {status} {size} "{request>headers>Referer>[0]}" "{request>headers>User-Agent>[0]}"` {
time_format "02/Jan/2006:15:04:05 -0700"
}
output file /root/data/caddy/log/:8080/access.log {
roll_size 25MB
roll_keep 10
roll_keep_for 24h
}
}
}
进阶
可以参考common_log的配置格式对日志格式进行自定义,可以针对个人喜好和项目需要灵活配置
例如这个简化版本
format transform `{ts} {request>headers>X-Forwarded-For>[0]:request>remote_ip} {request>host} {request>method} {request>uri} {status}` {
time_format "02/Jan/2006:15:04:05"
}
输出内容示例:
23/Dec/2023:17:53:24 192.168.0.24 subdomain.domain.name GET /index 200