openresty 的lua在返回响应后再日志里添加自定义的状态

理解了,你希望在 OpenResty 中将自定义状态输出到 log_format 中的日志格式里。你可以使用 Nginx 的变量机制将自定义状态记录到日志中。

步骤如下:

  1. 使用 set_by_lua 指令在请求处理过程中设置自定义变量。
  2. log_format 中引用该自定义变量。

以下是一个完整的示例配置:

http {
    lua_shared_dict my_dict 1m;

    # 定义日志格式
    log_format custom_log_format '$remote_addr - $remote_user [$time_local] "$request" '
                                 '$status $body_bytes_sent "$http_referer" '
                                 '"$http_user_agent" "$http_x_forwarded_for" '
                                 '$custom_status';

    # 将日志输出到文件
    access_log /var/log/nginx/access.log custom_log_format;

    server {
        listen 80;

        location / {
            # 使用 set_by_lua 设置自定义变量
            set_by_lua $custom_status '
                ngx.ctx.custom_status = "my_custom_status"
                return ngx.ctx.custom_status
            ';

            content_by_lua_block {
                -- 生成并发送响应
                ngx.say("Hello, OpenResty!")

                -- 设置自定义状态
                ngx.ctx.custom_status = "my_custom_status"
            }
        }

        log_by_lua_block {
            -- 确保自定义状态变量在 log_format 中设置
            ngx.var.custom_status = ngx.ctx.custom_status or "default_status"
        }
    }
}

在这个示例中:

  1. log_format 中定义了一个名为 custom_log_format 的日志格式,其中包括自定义变量 $custom_status
  2. access_log 指令指定将日志输出到 /var/log/nginx/access.log,并使用 custom_log_format 格式。
  3. set_by_lua 指令用于在处理请求时设置自定义变量 $custom_status。这里使用 Lua 代码将自定义状态存储在 ngx.ctx.custom_status 中,并返回该状态以设置 $custom_status
  4. log_by_lua_block 中,将 ngx.ctx.custom_status 设置为 ngx.var.custom_status,以确保该变量在 log_format 中引用。

这样,自定义状态将被包含在日志格式中,并输出到指定的日志文件中。确保重新加载 Nginx 配置文件以应用更改。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值