Separate varnishncsa logs per domain

Tested in ubuntu 16 / Varnish 4.1.9

Here a init.d script it starts a daemon per domain using varnishncsa:

#!/bin/sh                                                                                                                                                                                                  
                                                                                                                                                                                                            
### BEGIN INIT INFO                                                                                                                                                                                         
# Provides:          vhostlog
# Required-Start:    $local_fs $remote_fs $network
# Required-Stop:     $all
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts vhostlog service
# Description:       starts vhostlog service
### END INIT INFO

LogsPath=/var/log/vhostlog

case "$1" in
    start)

        while read domain; do
            varnishncsa -D -q 'ReqHeader:Host ~ "^(www\.)?'$domain'$"' \
	        -a -w $LogsPath/$domain-access.log \
	        -F '%h %l %u %t "%m %U %H" %s %b "%{Referer}i" "%{User-agent}i"'

        done < /path/to/domains-list.txt
                
        ;;
    stop)

        killall varnishncsa
        sleep 3

        ;;
    restart)

        $0 stop
        $0 start

        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
        ;;
esac

The content of file /path/to/domains-list.txt could be like this:

domain1.com
domain2.com
domain-test.org
mybeautifuldomain.net

If varnish is behind another proxy (like nginx to serve SSL for example) you can change %h by %{X-Forwarded-For}i or %{X-Real-IP}i.

Once created update it in init.d:

~ $ update-rc.d vhostlog defaults

An finally start it:

~ $ /etc/init.d/vhostlog start

Leave a Reply

Your email address will not be published. Required fields are marked *