微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 NGINX 访问日志中记录 mp4 文件的视频时长

如何解决在 NGINX 访问日志中记录 mp4 文件的视频时长

我正在尝试在 Nginx 访问日志中记录 mp4 文件的视频持续时间,这应该在客户端从服务器“获取一个 mp4 文件时发生。我配置了自定义日志格式如下:

log_format Nginx_custom_log '$remote_addr ... $request_uri $status $sent_http_content_type $video_duration';

access_log /var/log/Nginx/access.log Nginx_custom_log;

我可以添加自定义 HTTP 标头 - video_duration 指向视频文件的路径并手动分配值,但这需要每次添加视频并重新加载 Nginx 时更改 Nginx 配置:

location /path/video.mp4 {
    add_header video_duration 123456;
}

以下记录写入Nginx访问日志:

192.168.0.1 ... /path/video.mp4 206 video/mp4 123456

我还尝试在 Nginx 配置中配置 X-Content-Duration HTTP 标头(Firefox 不再支持),但没有记录任何值。

我找到了一个名为 ngx_http_mp4_module 的模块。它允许指定像 ?start=238.88&end=555.55 这样的参数,这让我相信 Nginx 能够读取 mp4 文件的元数据。

有没有办法在 Nginx 访问日志中记录 mp4 视频文件的持续时间,类似于如何记录文件content-length(以字节为单位)和 content-type(视频/mp4)?

解决方法

感谢 Alex 建议添加元数据文件并使用 Lua 读取它。以下是参考实现:

nginx.conf

location ~* \.(mp4)$ {
    set $directoryPrefix '/usr/local/openresty/nginx/html';
    set $metaFile '$directoryPrefix$request_uri.duration';

    set $mp4_header "NOT_SET";

    rewrite_by_lua_block {
        local f = assert(io.open(ngx.var.metaFile,"r"))
        ngx.var.mp4_header = f:read("*line")
        f:close()
    }

    add_header mp4_duration $mp4_header;
}

log_format nginxlog '$remote_addr ... "$request_uri" $status $sent_http_content_type $sent_http_mp4_duration';
access_log /usr/local/openresty/nginx/logs/access.log nginxlog;

请注意,$metaFile 指的是包含持续时间的元数据文件:

$directoryPrefix: /usr/local/openresty/nginx/html
$request_uri: /video/VideoABC.mp4
$metaFile: /usr/local/openresty/nginx/html/video/VideoABC.mp4.duration

access.log

192.168.0.1 ... "/video/VideoABC.mp4" 206 video/mp4 1234567890

mp4 和元数据文件路径

root@ubuntu: cd /usr/local/openresty/nginx/html/video/
root@ubuntu: ls
VideoABC.mp4  VideoABC.mp4.duration

root@ubuntu: cat VideoABC.mp4.duration
1234567890

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。