lua-resty-ga

将 nginx/openresty 访问日志发送到 Google Analytics

$ opm get BeanYoung/lua-resty-ga

lua-resty-ga

将 nginx/openresty 访问日志发送到 Google Analytics。

状态

此库已在 PoweredBy.Cloud 中使用,但在上线前您应该在您的系统中进行测试。

依赖

ledgetech/lua-resty-http >= 0.14

安装

    luarocks install lua-resty-ga

    opm get BeanYoung/lua-resty-ga

使用

    # ga.conf
    
    resolver 8.8.8.8 223.5.5.5 valid=3600s ipv6=off;
    
    lua_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
    
    lua_shared_dict ga_cache 128m;
    
    init_by_lua_block {
        local process = require 'ngx.process'
        process.enable_privileged_agent()
    }
    
    init_worker_by_lua_block {
        local process = require 'ngx.process'
        local ga = require 'resty.ga'
    
        if process.type() == 'privileged agent' then
            ngx.timer.every(1, ga.send)
        end
    }
    
    server {
        listen 0.0.0.0:80;
        location / {
            content_by_lua_block {
                ngx.say('ok')
            }
    
            log_by_lua_block {
                local ga = require 'resty.ga'
    
                -- Follow this link to create your tid.
                -- https://support.google.com/analytics/answer/10269537
                local tid = 'UA-188032216-1'
    
                -- Get cid from cookie or somewhere else based on your implementation
                local cid = 'user_id_0'
    
                local uip = ngx.var.remote_addr
                -- if your nginx is behind cloudflare
                local headers = ngx.req.get_headers()
                if headers['CF-Connecting-IP'] then
                    uip = headers['CF-Connecting-IP']
                end
    
                ga.collect(tid, cid, uip)
    
                -- Follow this link to create custom dimensions and custom metrics.
                -- https://support.google.com/analytics/answer/2709829?hl=en
                -- Then you can send custom dimensions and custom metrics like this.
                --ga.collect(tid, cid, uip, true)
            }
        }
    }

方法

collect

语法: ga.collect(tid, cid, uip, send_cd_and_cm)

收集当前请求的日志并推送到缓存。最好在日志阶段调用此方法 `log_by_lua_*`

tid 是您的 Google Analytics 跟踪 ID。请注意,这是 Universal Analytics 属性而不是 Google Analytics 4 属性。请按照此 链接 创建跟踪 ID。

cid 是 Google Analytics 的 客户端 ID

uip 是 Google Analytics 的 客户端 IP 地址

send_cd_and_cm 用于决定是否将自定义维度和自定义指标发送到 Google Analytics。在将此参数设置为 true 之前,必须在 Google Analytics 的管理面板中创建自定义维度和自定义指标。此外,自定义维度和自定义指标必须按以下顺序创建

| 自定义维度 | 索引 | 范围 | |-------------------|-------|-------| | 状态码 | 1 | HIT | | 内容类型 | 2 | HIT | | 缓存状态 | 3 | HIT | | HTTP 方法 | 4 | HIT |

| 自定义指标 | 索引 | 范围 | 格式类型 | |----------------|-------|-------|-------------| | 内容长度 | 1 | HIT | 整数 | | 响应时间 | 2 | HIT | 整数 |

send

语法: ga.send(premature)

弹出所有请求日志并发送到 Google Analytics 服务器。最好使用定时器在 特权代理 中每 1 秒调用一次此方法。

作者

陈冰玉 BeanYoung

作者

陈冰玉

许可证

apache2

依赖项

版本