1

I am trying to log the video duration of a mp4 file in NGINX access log, which should happen when a client 'GET' a mp4 file from the server. I have configured a custom log format as follows:

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;

I can add a custom HTTP header - video_duration pointing to the path of a video file and manually assigning the value, but this require changing nginx configuration every time a video is added and reloading nginx:

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

The following record is written to NGINX access log:

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

I also tried configuring the X-Content-Duration HTTP header (which is no longer supported by Firefox) in NGINX configuration but no value has been logged.

I found a module named ngx_http_mp4_module. It allows specifying arguments like ?start=238.88&end=555.55, which leads me to believe NGINX is capable of reading the metadata of a mp4 file.

Is there a way to log the duration of a mp4 video file in NGINX access log, similar to how a file's content-length (in bytes) and content-type (video/mp4) can be logged?

ac97cd
  • 11
  • 2
  • I would split this into 2 parts: in the same dir create second file(most probably text one) containing duration. Duration can be either in file body or in file name(like original_file mp4.duration). Then read this file with Lua and extract and log duration – Alex C Jan 07 '21 at 10:50

1 Answers1

0

Thanks Alex for suggesting to add a metadata file and read it using Lua. Here's the implementation for reference:

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;

Please note that $metaFile refers to the metadata file containing the duration:

$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 & metadata file path

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

root@ubuntu: cat VideoABC.mp4.duration
1234567890
ac97cd
  • 11
  • 2