26: Visitors

The visitors resource measures who reads an app without writing a row: each page pings the web server, the web server answers the ping itself and keeps it in its access log, and the Phlo Dashboard counts from that log. This chapter covers the modes an app can measure in and how to set up the web server for it: FrankenPHP and Caddy, Nginx, and Apache.

26.1: The ping

With visitors in the resources, a page sends a GET to /.phlo/beat/1 when it opens, every 20 seconds while it is visible, on a resize, on a navigation within the app, when it is hidden and when it comes back, and when it is left (with keepalive). The 1 is the version of the protocol. The fields ride URL-encoded in the query:

FieldWhatBound
nthe tab: eight letters in window.name8
ethe event: new for each ping, so a ping that arrives twice counts once8
pthe page view: new on each navigation12
uthe path, without query100
lthe language of the page8
w, hthe size of the window, in mode gdpr only with consent99999
a1 in app mode (standalone)
vactive, blurred or hidden
rthe domain that referred, empty for the site itself100
c1 with consent to all cookies (cookieChoice=all)
mthe mode of the app
iin mode internal: the user the app names64
sthe seconds the page was visible since the ping before120
pp, psafter a navigation: the page view before and the seconds still due to it12, 120

A device whose owner opens /visitors/uncounted/on once carries the cookie uncounted; the web server answers its pings but keeps them out of the log, so the owner's own visits are not counted. /visitors/uncounted/off takes it away.

Anyone can make a ping of their own: the dashboard validates every field and takes a ping as a sign of a browser, not as proof of a person. Bots that run JavaScript ping too and are told apart by their user agent and, for datacenters, by their address.

26.2: Modes

The mode says how much is measured. It is a setting of the app, and the owner of the app answers for the choice.

ModeForMeasures
gdpr (default)every public sitewithout consent only what the exemption for analytics allows: no recognition across days, no extra traits, no identity; the window size only with consent, through the cookie choice
consent-elsewhereconsent given another way: a contract, the terms of a service, another legal groundin full, without a cookie banner
internalan intranet or an app of known usersin full, with the user who is signed in

Use gdpr unless you can point to the consent or the relation that allows more. consent-elsewhere is for an app whose users agreed to measurement before they use it, in writing; a cookie banner would ask them again for what they already gave. internal is for an app of a company or a club for its own people, whose use is measured as part of the work, and names them.

static %visitors.mode = 'internal'
static %visitors.user => %session->user

static %visitors.user names the user in mode internal: whatever identifies a person in your app, cut to 64 characters. The page carries the mode in data-visitors on its body, and in mode internal the user in data-visitor; the resource puts them in %app->settings. An app that sets settings of its own merges them:

prop settings => [...visitors::settings(), 'theme' => 'dark']

A mode the resource does not know is an error, not a full measurement.

The access log stays complete in every mode, with the full IP address: what the dashboard derives from it, shows and keeps follows the mode. Keep the log on the server, readable by the dashboard alone, and keep it as short as you need (X.6).

26.3: What the web server does

  1. It answers a request for exactly /.phlo/beat/1 itself, before the app, with 204 and Cache-Control: no-store. An app rewrites what is not a file to app.php, so the match is on the path as the request came in.
  2. It keeps every request of the site in one JSON access log, one line per request, in the shape below. The query of a ping stays; the query of any other request may go, and should, as it can hold tokens.
  3. A ping that carries the cookie uncounted=1 gets its 204 and stays out of the log.

Without that, every ping reaches the app, which answers 404 to it, and nothing is counted.

The dashboard reads these fields of each line; a line it cannot read is skipped:

FieldWhat
tsthe time of the request, in seconds since 1970, with a fraction
request.client_ip (or request.remote_ip)the address of the client
request.methodthe method
request.hostthe host asked for
request.urithe path, with the query for a ping
request.headers.User-Agent[0]the user agent
request.headers.Referer[0], request.headers.X-Requested-With[0]kept for the views of traffic
durationhow long the answer took, in seconds
statusthe status of the answer
rootthe folder the site is served from: release/ is stage, a development build is dev, the rest is production

Point the dashboard at the log with [visits] log in its data/creds.ini (default /var/log/frankenphp/visits.log), and give the user it runs as read access to the log and its rotated files.

26.4: FrankenPHP and Caddy

The dashboard ships the snippet as caddy/visits.caddy. Import it once at the top of the Caddyfile, before the snippets, and put import phlo_visits in the snippet every site imports:

import /srv/control/dashboard/caddy/visits.caddy

(phlo_common) {
	encode zstd br gzip
	import phlo_visits
}

This is the snippet:

(phlo_visits) {
	@phlo_beat vars {http.request.orig_uri.path} /.phlo/beat/1
	handle @phlo_beat {
		@phlo_uncounted header_regexp Cookie (?:^|;\s*)uncounted=1(?:;|$)
		log_skip @phlo_uncounted
		header Cache-Control no-store
		respond 204
	}
	log_append root {http.vars.root}
	log phlo_visits {
		output file {$PHLO_VISITS_LOG:/var/log/frankenphp/visits.log} {
			mode 0640
			roll_size {$PHLO_VISITS_ROLL_SIZE:100MiB}
			roll_keep {$PHLO_VISITS_ROLL_KEEP:30}
			roll_keep_for {$PHLO_VISITS_KEEP_FOR:720h}
		}
		format filter {
			request>uri multi_regexp {
				regexp ^(/\.phlo/beat/1)\? $1#
				regexp \?.*$ ""
				regexp ^(/\.phlo/beat/1)# $1?
			}
			request>headers>Cookie delete
			request>headers>Authorization delete
			request>tls delete
			resp_headers delete
		}
	}
}

The match is on orig_uri, the path before any rewrite, so the ping is answered whatever the site rewrites to app.php. The three regular expressions take the query off every request but the ping. A site with a log of its own keeps it beside this one.

The log rolls at PHLO_VISITS_ROLL_SIZE into gzipped files beside it, of which it keeps PHLO_VISITS_ROLL_KEEP for at most PHLO_VISITS_KEEP_FOR; set them in the environment of the service. The reader follows the rolled and compressed files in their order.

26.5: Nginx

In the http block, a log format with the fields of the dashboard, the query kept for the ping alone, and the ping of an uncounted device left out:

map $request_uri $phlo_uri {
	~^(/\.phlo/beat/1\?.*)$  $1;
	~^([^?]*)                $1;
}

map "$uri:$cookie_uncounted" $phlo_logged {
	"/.phlo/beat/1:1"  0;
	default            1;
}

log_format phlo_visits escape=json '{"ts":$msec,"request":{"client_ip":"$remote_addr","method":"$request_method","host":"$host","uri":"$phlo_uri","headers":{"User-Agent":["$http_user_agent"],"Referer":["$http_referer"],"X-Requested-With":["$http_x_requested_with"]}},"duration":$request_time,"status":$status,"root":"$document_root"}';

In each server that is counted, the log and the exact location of the ping, which goes before any try_files to the app:

server {
	server_name shop.example;
	root /srv/shop/www;
	access_log /var/log/nginx/visits.log phlo_visits if=$phlo_logged;

	location = /.phlo/beat/1 {
		add_header Cache-Control no-store always;
		return 204;
	}

	location / {
		try_files $uri /app.php$is_args$args;
	}
}

Behind a proxy, set real_ip_header and set_real_ip_from so $remote_addr is the client.

26.6: Apache

In each VirtualHost that is counted: two log formats, one that keeps the query of the ping and one that drops it for every other request, the ping answered with mod_rewrite before the app, and its header with mod_headers. root is written as the folder of the site, as Apache has no variable for it in a log:

SetEnvIf Request_URI "^/\.phlo/beat/1$" phlo_beat
SetEnvIfExpr "reqenv('phlo_beat') == '1' && %{HTTP_COOKIE} =~ /(^|;\s*)uncounted=1(;|$)/" phlo_uncounted

<VirtualHost *:443>
	ServerName shop.example
	DocumentRoot /srv/shop/www

	LogFormat "{\"ts\":%{sec}t.%{msec_frac}t,\"request\":{\"client_ip\":\"%a\",\"method\":\"%m\",\"host\":\"%{Host}i\",\"uri\":\"%U%q\",\"headers\":{\"User-Agent\":[\"%{User-Agent}i\"],\"Referer\":[\"%{Referer}i\"],\"X-Requested-With\":[\"%{X-Requested-With}i\"]}},\"duration\":%T,\"status\":%>s,\"root\":\"/srv/shop/www\"}" phlo_ping
	LogFormat "{\"ts\":%{sec}t.%{msec_frac}t,\"request\":{\"client_ip\":\"%a\",\"method\":\"%m\",\"host\":\"%{Host}i\",\"uri\":\"%U\",\"headers\":{\"User-Agent\":[\"%{User-Agent}i\"],\"Referer\":[\"%{Referer}i\"],\"X-Requested-With\":[\"%{X-Requested-With}i\"]}},\"duration\":%T,\"status\":%>s,\"root\":\"/srv/shop/www\"}" phlo_request
	CustomLog /var/log/apache2/visits.log phlo_ping "expr=reqenv('phlo_beat') == '1' && reqenv('phlo_uncounted') != '1'"
	CustomLog /var/log/apache2/visits.log phlo_request "expr=reqenv('phlo_beat') != '1'"

	RewriteEngine On
	RewriteRule ^/\.phlo/beat/1$ - [R=204,L]
	<Location "/.phlo/beat/1">
		Header always set Cache-Control "no-store"
	</Location>
</VirtualHost>

Two things of Apache to know: %T gives whole seconds, so a page counts as slow from one second on, which is the default of the dashboard; and Apache writes a byte it cannot print, and each byte of a character outside ASCII such as the é of /café, as \xhh, which is no JSON: the reader of the dashboard turns those back into the characters they were, so such a line counts as any other. Behind a proxy, use mod_remoteip so %a is the client.

26.7: Rotation and retention

Caddy rolls the log itself (X.4). For Nginx and Apache, logrotate does it; name the rolled files the way the reader follows them, visits-<time>.log, and compress one round later, so the reader can finish a file before it is packed:

/var/log/nginx/visits.log {
	size 100M
	rotate 30
	maxage 30
	dateext
	dateformat -%Y-%m-%dT%H-%M-%S
	extension .log
	compress
	delaycompress
	missingok
	notifempty
	create 0640 www-data adm
	postrotate
		[ -s /run/nginx.pid ] && kill -USR1 $(cat /run/nginx.pid)
	endscript
}

For Apache, use the path of its log and apachectl graceful after the rotation. logrotate runs once a day by default; a busy log needs it every hour.

How long the log is kept is the retention of the full IP addresses in it: keep it as short as your counts allow, 30 days at most for a public site in mode gdpr. The number of files is a limit too: a site that crawlers walk through can write hundreds of MB a day, and 30 files of 100 MB then hold a few days, not 30. The dashboard reads the log every time it is looked at or polled, so a short retention loses nothing it already counted.

We use essential cookies to make this site work. With your permission we also use analytics to improve the site.