You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为nginx escape=json的log_format配置缺省连字符替代空值?

Nginx日志escape=json下替换空变量为连字符的解决方案

nginx官方文档确实只在escape=default时默认将空变量替换为-,但在escape=json模式下,我们可以通过预处理变量的方式实现相同效果,推荐使用map指令(性能更优),具体步骤如下:

方法一:使用map指令预处理变量

在http块中定义map规则,针对每个需要处理的变量,判断其是否为空,为空则返回连字符-,否则保留原变量值:

http {
    # 处理User-Agent变量,空值替换为-
    map $http_user_agent $ua_with_dash {
        default $http_user_agent;
        "" "-";
    }

    # 处理Referer变量,空值替换为-
    map $http_referer $referer_with_dash {
        default $http_referer;
        "" "-";
    }

    # 你的其他http配置...

    log_format json_log escape=json '{
        "time": "$time_iso8601",
        "remote_addr": "$remote_addr",
        "user_agent": "$ua_with_dash",
        "referer": "$referer_with_dash"
    }';

    access_log /var/log/nginx/access.log json_log;
}

map是nginx推荐的变量处理方式,不会引入额外的请求处理开销,适合批量处理多个变量。

方法二:使用set+if指令(不推荐,仅作备选)

如果场景简单,也可以在server块中用set和if指令逐个处理变量,但if在nginx中属于条件分支,可能对性能有轻微影响:

server {
    # 处理User-Agent变量
    set $ua_with_dash $http_user_agent;
    if ($ua_with_dash = "") {
        set $ua_with_dash "-";
    }

    # 你的其他server配置...

    log_format json_log escape=json '{
        "time": "$time_iso8601",
        "remote_addr": "$remote_addr",
        "user_agent": "$ua_with_dash"
    }';
}

两种方法的核心逻辑都是先将空变量替换为-,再传入escape=json的日志格式中,这样最终日志里的空变量就会显示为-,同时保留json转义的特性。

内容的提问来源于stack exchange,提问作者SoftShell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 15:48:47