nginx 视频流统计

nginx video streaming statistics

我正在使用 ngx_http_mp4_module 从我的服务器流式传输视频。我有一个可以被多个域访问的服务器。

我使用以下配置 nginx:

location /content/ {
    mp4;
    mp4_buffer_size       1m;
    mp4_max_buffer_size   5m;
}

我将所有视频存储在我服务器的 /content 文件夹下,并通过 url 访问它们:http://example.com/content/testvideo.mp4

由于我可以使用多个域访问我的服务器,因此我可以通过访问

来观看相同的视频

http://mydomain1.com/content/testvideo.mp4

http://mydomain2.com/content/testvideo.mp4

问题是:我如何记录关于 url 视频被观看的统计信息以及观看了多少秒?

设置包含 $host$request_time 变量的日志记录格式。

在该位置指令中使用该日志记录格式。

它在 Nginx 网站上有完整的记录以及可用于包含在日志中的变量列表,以下属于 http 块并且是标准 combined 日志格式的修改版本,其中包含两个上面的变量添加到最后:

log_format streaming '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" $host $request_time';

这定义了一个名为 streaming 的日志格式,变量 $host 显然是来自客户端请求的主机名。根据文档,$request_time 是:

request processing time in seconds with a milliseconds resolution; time elapsed between the first bytes were read from the client and the log write after the last bytes were sent to the client

如果您的视频是 CBR,您还可以使用 $bytes_sent 记录传输到客户端的总数据并计算以这种方式传输的视频的持续时间。

一旦您定义了您的自定义日志格式,然后在您的位置块中为流式传输设置一个指令,以请求该位置使用该格式进行日志记录,如下所示:

access_log /path/to/log/video.log streaming;

这只是写入日志的路径,streaming 是此日志使用的日志格式。

现在 Nginx 将创建一个日志文件,其中包含对该位置的所有请求,无论客户端访问了哪个域。

也许您更喜欢每个域的单独日志?没问题,只需使用 $host 变量作为 access_log 指令

中路径的一部分

access_log /path/to/log/$host-video.log streaming;

现在每个域都会有自己的日志。 example.com-video.log, example.net-video.log 等

也许你两个都想要?没问题,您可以在同一级别指定多个 access_log 指令:

access_log /path/to/log/video.log streaming;
access_log /path/to/log/$host-video.log streaming;