Linux Lunatix

Who reads my blog? Statistics without sacrificing your privacy

hans_olo
| 11 minutes

After the two series went live, I wanted to know if anybody reads them. Which posts get attention, where do the readers come from, and roughly from which part of the world?

The usual answer is an analytics script on every page. I didn’t want that. This site has no JavaScript, no cookies and no external resources, and the privacy page promises exactly that. So the rules were:

The web server already writes an access log for every request. Everything I want to know is in there. This post turns that log into a report.

What you’ll have at the end

Two sources for two questions

SourceWhat it knowsAddressesUsed for
Traefik’s metricsrequests per router, status code, durationnoGrafana panels
Traefik’s access logtime, path, status, size, referrer, user agent, client addressyesthe GoAccess report

The metrics are cheap and harmless, but they can’t tell one page from another. For pages, referrers and countries I need the access log. So the access log gets the careful treatment.

Step 1: the access log

Traefik runs on the web host, vps2, in the host network namespace (see the Traefik post). That is why it sees the real client address. It writes the access log as JSON to stdout, and from there it goes into the journal:

# traefik.yml
accessLog:
  format: json
  fields:
    headers:
      defaultMode: drop
      names:
        User-Agent: keep
        Referer: keep

defaultMode: drop removes all request headers from the log. I keep only two: the user agent, for the browser statistics and to filter bots, and the referrer, to see where readers come from. Cookies and authorisation headers never get into the log.

One entry, shortened:

{"ClientHost": "203.0.113.57", "RequestHost": "www.example.org", "RequestPath": "/blog/why-ssh-certificates/",
 "DownstreamStatus": 200, "entryPointName": "https", "StartUTC": "2026-11-23T10:04:05.123456789Z",
 "request_User-Agent": "Mozilla/5.0 ...", "request_Referer": "https://example.com/some-forum/"}

Step 2: from the journal to GoAccess, with shortened addresses

GoAccess is a log analyser that writes a single HTML file. It can keep its data between runs (--persist, --restore), so each run only needs the new lines. It reads the classic “combined” log format.

A small Python script does the work in between. It runs once an hour as the app user svc.

Read only the new lines

The journal gives every entry a cursor. The script saves the last cursor it processed and asks for the lines after it on the next run:

def new_lines():
    """New Traefik journal entries since the last run: (combined log lines, last cursor)."""
    cmd = ["journalctl", "--user", "-u", "traefik", "-o", "json", "--no-pager"]
    if os.path.exists(CURSOR):
        cmd.append("--after-cursor=" + open(CURSOR).read().strip())
    out, cursor = [], None
    with subprocess.Popen(cmd, stdout=subprocess.PIPE, text=True) as p:
        for raw in p.stdout:
            rec = json.loads(raw)
            cursor = rec["__CURSOR"]
            msg = rec.get("MESSAGE")
            if not isinstance(msg, str) or not msg.startswith("{"):
                continue
            try:
                line = to_clf(json.loads(msg))
            except (ValueError, KeyError):
                continue
            if line:
                out.append(line)
    return out, cursor

The script writes the new cursor only after GoAccess has succeeded. If a run fails or the host is off, the next run picks up the same lines. A request is never counted twice and never lost.

Traefik also writes normal log messages to the same journal, for example when it pulls an image. Those are not JSON, and the script skips them.

Keep the blog, shorten the address

HOSTS = {"www.example.org", "example.org"}
ENTRYPOINT = "https"


def anonymise(addr):
    try:
        ip = ipaddress.ip_address(addr)
    except ValueError:
        return "0.0.0.0"
    prefix = 24 if ip.version == 4 else 48
    return str(ipaddress.ip_network(f"{ip}/{prefix}", strict=False).network_address)


def to_clf(entry):
    """One Traefik JSON access log entry -> a combined log line, or None."""
    if entry.get("RequestHost") not in HOSTS or entry.get("entryPointName") != ENTRYPOINT:
        return None
    return '{} - - [{}] "{} {} {}" {} {} "{}" "{}"'.format(
        anonymise(entry.get("ClientHost", "")), clf_time(entry["StartUTC"]),
        q(entry.get("RequestMethod")), q(entry.get("RequestPath")), q(entry.get("RequestProtocol")),
        entry.get("DownstreamStatus", 0), entry.get("DownstreamContentSize", 0),
        q(entry.get("request_Referer")), q(entry.get("request_User-Agent")))

The same Traefik serves other sites too, so the script keeps only the blog’s host names. It also keeps only the https entrypoint. The plain HTTP requests are only redirects.

203.0.113.57 becomes 203.0.113.0, and 2001:db8:1234:5678::1 becomes 2001:db8:1234::. A /24 has 256 IPv4 addresses. A /48 is at least one whole customer network, often the networks of many customers, so it doesn’t point to a device. The country lookup still works, because geolocation databases list networks, not single addresses.

The cost: GoAccess counts a “visitor” as one address, one day and one user agent. Two readers in the same /24 with the same browser on the same day count as one. For my question that is close enough.

Two small helpers complete it. q() escapes quotes in the referrer and the user agent, so a crafted header can’t break the log format. clf_time() writes the date as 23/Nov/2026:10:04:05 +0000 with its own month names, so the result doesn’t depend on the host’s locale.

Run GoAccess in a container without network

cmd = ["podman", "run", "--rm", "-i", "--network", "none",
       "-v", f"{DB}:/db:Z", "-v", f"{HTML}:/html:z"]
geo = []
if os.path.exists(MMDB):
    cmd += ["-v", f"{GEO}:/geo:ro,Z"]
    geo = ["--geoip-database=/geo/dbip-country-lite.mmdb"]
cmd += [IMAGE, "-", "--log-format=COMBINED", "--persist", "--restore", "--db-path=/db",
        "--keep-last=365", "--ignore-crawlers", "--no-query-string",
        "--html-report-title=example.org", "-o", "/html/new.html"] + geo
subprocess.run(cmd, input="".join(l + "\n" for l in lines), text=True, check=True)
os.replace(os.path.join(HTML, "new.html"), report)
if cursor:
    open(CURSOR, "w").write(cursor)

The options that matter:

I pinned the image to docker.io/allinurl/goaccess:1.12. The data format of --persist can change between versions, and I want to decide when that happens.

The html volume gets :z (shared), not :Z, because the web server container in step 5 reads the same directory. See the SELinux post for the difference.

Step 3: countries

GoAccess reads MaxMind-format databases. MaxMind’s free database needs an account and a licence key. DB-IP’s IP to Country Lite is free without an account, under CC BY 4.0, and comes in the same format. It is updated monthly, so the script downloads it once a month:

def update_geoip():
    """Download this month's DB-IP Country Lite once (fall back to last month's)."""
    today = datetime.date.today()
    if os.path.exists(MMDB) and datetime.date.fromtimestamp(os.path.getmtime(MMDB)) >= today.replace(day=1):
        return
    last = today.replace(day=1) - datetime.timedelta(days=1)
    for d in (today, last):
        url = f"https://download.db-ip.com/free/dbip-country-lite-{d:%Y-%m}.mmdb.gz"
        try:
            # DB-IP refuses Python's default User-Agent (403)
            req = urllib.request.Request(url, headers={"User-Agent": "blogstats/1.0"})
            with urllib.request.urlopen(req, timeout=120) as r, open(MMDB + ".tmp", "wb") as f:
                shutil.copyfileobj(gzip.GzipFile(fileobj=r), f)
            os.replace(MMDB + ".tmp", MMDB)
            return
        except Exception as e:
            print(f"GeoIP {url}: {e}", file=sys.stderr)
    # keep the old database, if any

On the first days of a month, this month’s file may not exist yet. Then the script takes last month’s file. If both downloads fail, it keeps the old database.

The lookup uses the shortened address. For the country that makes no difference. I started with DB-IP’s city database and went back to countries. On a shortened address the city is a guess, and the countries were all I wanted to know.

Step 4: once an hour

Two user units for svc:

# ~/.config/systemd/user/blogstats.service
[Unit]
Description=GoAccess report (anonymised Traefik access log)
After=traefik.service

[Service]
Type=oneshot
ExecStart=%h/.local/bin/blogstats
# ~/.config/systemd/user/blogstats.timer
[Unit]
Description=Hourly GoAccess report

[Timer]
OnCalendar=hourly
RandomizedDelaySec=5m
Persistent=true

[Install]
WantedBy=timers.target

Persistent=true runs a missed run after a reboot. Thanks to the cursor, one late run catches up with all the lines.

In my Ansible setup this is one more app directory for the quadlet_app role from the Ansible post:

# apps/blogstats/app.yml
dirs:
  - {path: blogstats}
  - {path: blogstats/db}
  - {path: blogstats/html}
  - {path: blogstats/geo}
units: [blogstats-web.service]
enable: [blogstats.timer]

The script lives in apps/blogstats/files/.local/bin/blogstats, the units in files/.config/systemd/user/. The backup excludes blogstats/geo, because it’s a download.

Step 5: the report, for my eyes only

The report is a static file. static-web-server serves it:

# blogstats-web.container
[Container]
ContainerName=blogstats-web
Image=docker.io/joseluisq/static-web-server:2
AutoUpdate=registry
PublishPort=127.0.0.1:8104:80
Environment=SERVER_ROOT=/public
# Shared with the GoAccess run of blogstats.service: relabelled with z (not Z)
Volume=%h/blogstats/html:/public:ro,z
Label=traefik.enable=true
# monitor: Traefik's entrypoint on :8082, open only in the monitoring zone (wg-mon)
Label=traefik.http.routers.blogstats.rule=Host(`stats.example.net`)
Label=traefik.http.routers.blogstats.entrypoints=monitor
Label=traefik.http.services.blogstats.loadbalancer.server.port=80

The router listens on Traefik’s monitor entrypoint, not on https. That entrypoint is port 8082, and the firewall opens it only in the zone of the monitoring tunnel from the monitoring post. From the internet, port 8082 is closed.

# traefik.yml on vps2
entryPoints:
  monitor:
    address: ":8082"
    observability:
      accessLogs: false

accessLogs: false: Prometheus scrapes this entrypoint every 15 seconds. Those requests don’t belong in the access log.

At home, the Traefik of home1 publishes the report with a real certificate. It forwards to the web host’s tunnel address:

# dynamic_conf.yml on home1
http:
  routers:
    blogstats:
      rule: "Host(`stats.example.net`)"
      entryPoints:
        - https
      tls:
        certResolver: default
      middlewares:
        - secureHeaders
      service: blogstats
  services:
    blogstats:
      loadBalancer:
        servers:
          - url: "http://10.99.0.12:8082"

The home Traefik is only reachable from the LAN and over WireGuard. A local DNS record in Pi-hole points stats.example.net to it. The public DNS has no record for that name.

Step 6: Traefik’s counters in Grafana

For the Grafana panels, Traefik exports Prometheus metrics on the same monitor entrypoint:

# traefik.yml on vps2
metrics:
  prometheus:
    entryPoint: monitor
    addRoutersLabels: true

addRoutersLabels adds the router name to each counter. One router is one site, so the panels show requests per site. Prometheus at home scrapes 10.99.0.12:8082 through the tunnel.

The panel “Requests per hour”:

sum by (router) (increase(traefik_router_requests_total{job="traefik-remote",
    router=~".+@docker", router!="blogstats@docker", code=~"2..|3.."}[1h]))

A second panel shows 4xx and 5xx per hour. It’s mostly scanners that look for wp-login.php and similar pages.

Check it

systemctl --user start blogstats.service
journalctl --user -u blogstats.service -n 3
ls -l ~/blogstats/html/index.html

The first run read the whole journal, four days of access log: 28040 new requests. After that, each run reports only the requests of the last hour.

Then look into the data that GoAccess stores. Take a full address from the access log, and its shortened form:

grep -rlaF 203.0.113.57 ~/blogstats/db || echo clean   # clean
grep -rlaF 203.0.113.0 ~/blogstats/db                  # .../IS32_HOSTS_MTRC_DATAMAP.db

The full address is nowhere. The shortened one is in the hosts table, as it should be.

And from outside, the report must not answer:

curl -s -m 5 http://vps2.example.org:8082/ || echo blocked

What bit me

What it costs

The report only knows what the web server has to know anyway. The access log still contains full addresses, but only on the web host, and only for 7 days:

# /etc/systemd/journald.conf.d/00-size.conf on vps2
[Journal]
SystemMaxUse=500M
MaxRetentionSec=7day
MaxFileSec=1day

MaxRetentionSec deletes journal files whose entries are all older than 7 days. journald starts a new file only once a month by default, so a file could hold entries for weeks past the limit. MaxFileSec=1day starts a new file every day, and old entries go within a day of the limit. The journal isn’t in the backup. The privacy page says what I keep and for how long, and who is responsible. GoAccess and its data only ever see the shortened addresses.

Further reading

Previous: Removing the plain SSH keys Next: Cleaning up an old notes repository

Related content

Cleaning up an old notes repository
CI deploys without a deploy key
Why SSH certificates