error_log_write
`error_log_write` 指令允许在 NGINX 配置中基于指定条件有条件地记录错误消息。
Conditional error log entries in configuration
·
httpserverlocation
语法error_log_write [level=log_level] message=text [if=condition];
默认值none
上下文http, server, location
参数1-3
说明
error_log_write 指令是 ngx_http_error_log_write_module 的一部分,根据指定参数有条件地写入自定义错误日志条目。该指令支持多种上下文,包括 http、server 和 location,在服务器层次的不同级别提供配置错误日志的灵活性。
该指令最多接受三个参数:level、message 和可选的 if 条件。level 参数指定日志条目的严重性(例如 info、warn),而 message 参数包含要记录的文本。if 条件决定何时写入日志。如果条件满足(结果求值为 true),NGINX 会以定义的日志级别记录指定的消息。如果条件不满足且设置了 negative 标志,则该消息将不被记录。
该指令主要用于根据运行时条件创建细粒度的日志策略,帮助开发者管理日志噪音并关注与特定操作上下文相关的重要事件。
配置示例
server {
listen 127.0.0.1:80;
server_name localhost;
error_log_write message="server test log" if=$arg_test;
location / {
error_log_write level=warn message="auth required" if!=$http_authorization;
auth_basic "auth required";
auth_basic_user_file conf/htpasswd;
proxy_pass http://example.upstream.com;
}
}⚠
确保 if 条件被正确评估,以避免意外的日志遗漏。
⚠
检查 NGINX 的日志级别设置,确保指定的日志级别按预期捕获消息。
⚠
定期重新审查匹配条件,尤其当 if 条件依赖于应用逻辑或请求参数的变化时。