matomoicecast

How to track Icecast2 visits with Matomo?


My beloved web radio has an icecast2 instance and it just works. We have also a Matomo instance to track visits on our WordPress website, using only Free/Libre and open source software.

The main issue is that, since Matomo tracks visits via JavaScript, direct visits to the web-radio stream are not intercepted by Matomo as default.

How to use Matomo to track visits to Icecast2 audio streams?


Solution

  • Yep it's possible. Here my way.

    First of all, try the Matomo internal import script. Be sure to set your --idsite= and the correct path to your Matomo installation:

    su www-data -s /bin/bash
    python2.7 /var/www/matomo/misc/log-analytics/import_logs.py --show-progress --url=https://matomo.example.com --idsite=1 --recorders=2 --enable-http-errors --log-format-name=icecast2 --strip-query-string /var/log/icecast2/access.log
    

    NOTE: If you see this error

    [INFO] Error when connecting to Matomo: HTTP Error 400: Bad Request
    

    In this case, be sure to have all needed plugins activated:


    So, if the script works, it should start printing something like this:

    0 lines parsed, 0 lines recorded, 0 records/sec (avg), 0 records/sec (current)
    Parsing log /var/log/icecast2/access.log...
    1013 lines parsed, 200 lines recorded, 99 records/sec (avg), 200 records/sec (current)
    

    If so, immediately stop the script to avoid to import duplicate entries before installing the definitive solution.

    To stop the script use CTRL+C.

    Now we need to run this script every time the log is rotated, before rotation.

    The official documentation suggests a crontab but I don't recommend this solution. Instead, I suggest to configure logrotate instead.

    Configure the file /etc/logrotate.d/icecast2. From:

    /var/log/icecast2/*.log {
           ...
           weekly
           ...
    }
    

    To:

    /var/log/icecast2/*.log {
            ...
            daily
            prerotate
                    su www-data -s /bin/bash --command 'python2.7 ... /var/log/icecast2/access.log' > /var/log/logrotate-icecast2-matomo.log
            endscript
            ...
    }
    

    IMPORTANT: In the above example replace ... with the right command.

    Now you can also try it manually:

    logrotate -vf /etc/logrotate.d/icecast2
    

    From another terminal you should be able to see its result in real-time with:

    tail -f /var/log/logrotate-icecast2-matomo.log
    

    If it works it means everything will work perfectly and automatically, importing all visits every day, without any duplicate and without missing any lines.

    More documentation here about the import script itself:

    https://github.com/matomo-org/matomo-log-analytics

    More documentation here about logrotate:

    https://linux.die.net/man/8/logrotate