IntermediateLesson 8 of 127 min read

Understanding Visitors: Analytics from a Real Server Log, Checked with awk

Learn what your visitors do from a web server log: parse a generated log of 5,000 requests, count visitors, page views, top pages, errors and the share of visitors who leave after one page, and verify every figure with Unix tools.

In this lesson you will

  • Read a web server log line
  • Count visitors, page views and bounces
  • Separate bots from people
  • Verify counts with Unix tools

About 28 minutes

Who is looking at the candles?

Priya has had the site for a month and wants to know whether anyone is looking at it, and at what. Her builder has a built-in analytics screen, and its numbers come from somewhere: either from scripts running in the visitor’s browser, as in many analytics products, or from the web server’s log, which records every request. A server log is the simplest and most honest source, because it needs no scripts and no cookies, and every line is one request in the common log format: the address of the visitor, the time, the request, the status code and the size of the reply, and in the combined format also the page they came from and their browser.

The numbers you read from analytics have exact meanings that are easy to confuse. A page view is one request for a page. A visitor, in a log, is usually counted by address, which is only an approximation: several people can share one address, and one person can have several. A session is a visit, a group of requests from the same visitor close in time. The bounce rate is the share of sessions that viewed only one page, which is not automatically bad, since a visitor who finds the opening hours on the home page and leaves has had a good visit. Logs also contain requests from bots, search engine crawlers and scanners, and from people loading images and style sheets, so the first step is to decide what to count: here, successful requests for pages, not for images, from visitors that are not bots.

Term Meaning Caution
Request One line of the log Includes images and files
Page view A request for a page Reloads count again
Visitor Distinct address (approximation) Shared and changing addresses
Bounce A visit with a single page view Not always bad
Bot Crawler or scanner Should not be counted as a person
import random, json
rng = random.Random(2024)
PAGES = ["/", "/candles", "/candles/lavender", "/candles/pine", "/candles/honey", "/about", "/delivery", "/contact", "/blog/post-1"]
W = [30, 18, 10, 8, 8, 6, 6, 5, 4]
REF = ["-", "https://www.google.example/", "https://social.example/", "https://news.example/"]
RW = [40, 30, 20, 10]
UA = ["Mozilla/5.0 (iPhone; Mobile)", "Mozilla/5.0 (Windows NT 10.0)", "Mozilla/5.0 (Android; Mobile)", "Mozilla/5.0 (Macintosh)", "Googlebot/2.1 (+http://www.google.example/bot.html)", "ScannerBot/1.0"]
UW = [30, 28, 20, 12, 6, 4]
lines = []; ips = ["10.0.%d.%d" % (rng.randrange(0, 40), rng.randrange(1, 255)) for _ in range(700)]
for i in range(5000):
    ip = rng.choice(ips); page = rng.choices(PAGES, W)[0]; r = rng.random()
    status = 200 if r < 0.93 else 404 if r < 0.98 else 301
    if status == 404: page = rng.choice(["/wp-login.php", "/old-promo", "/favicon.ico"])
    kind = rng.random()
    path = page if kind < 0.7 else "/static/style.css" if kind < 0.85 else "/img/" + rng.choice(["a", "b", "c"]) + ".jpg"
    if status == 404: path = page
    lines.append('%s - - [10/Mar/2024:%02d:%02d:%02d +0000] "GET %s HTTP/1.1" %d %d "%s" "%s"' % (ip, 8 + i * 12 // 5000, (i * 7) % 60, (i * 13) % 60, path, status, rng.randrange(300, 90000), rng.choices(REF, RW)[0], rng.choices(UA, UW)[0]))
import sys
open(sys.argv[1], "w").write("\n".join(lines) + "\n")
print("wrote", len(lines), "lines | first line:"); print(lines[0])
wrote 5000 lines | first line:
10.0.23.4 - - [10/Mar/2024:08:00:00 +0000] "GET /contact HTTP/1.1" 200 40974 "https://www.google.example/" "Mozilla/5.0 (iPhone; Mobile)"
f="$1"
echo "requests: $(wc -l < $f)"
echo "status counts: $(awk '{print $9}' $f | sort | uniq -c | sort -k2 | awk '{printf "%s=%s ", $2, $1}')"
echo "bot requests: $(grep -ci 'bot' $f)"
awk '$9 == 200 && $7 !~ /^\/(static|img)\// && tolower($0) !~ /bot/ {print $1, $7}' $f > pages.txt
echo "page views: $(wc -l < pages.txt)"
echo "visitors (distinct addresses): $(awk '{print $1}' pages.txt | sort -u | wc -l)"
echo "visitors with one page view (bounces): $(awk '{print $1}' pages.txt | sort | uniq -c | awk '$1 == 1' | wc -l)"
echo "top pages:"; awk '{print $2}' pages.txt | sort | uniq -c | sort -k1,1nr -k2,2 | head -3 | awk '{printf "  %s %s\n", $1, $2}'
requests: 5000
status counts: 200=4643 301=112 404=245 
bot requests: 541
page views: 2896
visitors (distinct addresses): 664
visitors with one page view (bounces): 40
top pages:
  924 /
  558 /candles
  298 /candles/lavender
import re, collections
rx = re.compile(r'^(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+) [^"]*" (\d+) (\d+) "([^"]*)" "([^"]*)"$')
rows = [rx.match(x).groups() for x in open(r"/tmp/log-g9rmbduq/access.log").read().strip().split("\n")]
pages = [r for r in rows if r[4] == "200" and not r[3].startswith(("/static/", "/img/")) and "bot" not in r[7].lower()]
by_ip = collections.Counter(r[0] for r in pages)
print("page views:", len(pages), "| visitors:", len(by_ip), "| bounce rate: %.1f%%" % (100 * sum(1 for c in by_ip.values() if c == 1) / len(by_ip)))
print("pages per visitor: %.2f" % (len(pages) / len(by_ip)))
print("top pages:", collections.Counter(r[3] for r in pages).most_common(3))
print("traffic sources:", {k: v for k, v in collections.Counter(r[6] for r in pages).most_common()})
ua = collections.Counter("phone" if "Mobile" in r[7] else "computer" for r in pages)
print("page views from phones vs computers:", dict(ua))
print("missing pages people asked for:", collections.Counter(r[3] for r in rows if r[4] == "404").most_common(3))
page views: 2896 | visitors: 664 | bounce rate: 6.0%
pages per visitor: 4.36
top pages: [('/', 924), ('/candles', 558), ('/candles/lavender', 298)]
traffic sources: {'-': 1162, 'https://www.google.example/': 857, 'https://social.example/': 588, 'https://news.example/': 289}
page views from phones vs computers: {'phone': 1608, 'computer': 1288}
missing pages people asked for: [('/wp-login.php', 83), ('/old-promo', 82), ('/favicon.ico', 80)]

The generator wrote a repeatable log of 5,000 requests from 700 addresses to the sample site, with pages, style sheets and images, mostly successful requests and some missing pages, and a mix of browsers and two bots. The first job is to decide what counts, and the awk pipeline and the Python script made the same decision: successful (status 200) requests for pages, not for style sheets and images, and not from bots. With that rule the log contains 2,896 page views from 664 distinct visitors, an average of 4.36 pages per visitor. Of the 5,000 requests, 541 came from bots, which a naive count of lines would have counted as customers.

Of the 664 visitors, 40 viewed a single page, a bounce rate of 6.0 percent. The three most viewed pages are / (924), /candles (558), /candles/lavender (298). The traffic sources, taken from the referrer field, are: direct or unknown 1162, www.google.example 857, social.example 588, news.example 289. Phones account for 1608 of the page views and computers for 1288. The missing pages that visitors or scanners asked for most were /wp-login.php (83 times), /old-promo (82 times), /favicon.ico (80 times), which is worth a look: a missing page that real visitors ask for, such as an old promotion, deserves a redirect, and requests for wp-login.php are scanners probing for a login page that Priya’s builder does not even have.

Independent check: the same questions were answered by a different toolbox: awk, sort, uniq and grep, which read the file as plain text, and by a Python script with a regular expression. The number of requests, the counts per status code, the number of bot requests, the page views, the distinct visitors, the single-page visitors and the three top pages agree exactly between them, and with the numbers computed in the lesson’s own code. Agreement across tools shows that the parsing is right, and not that the definitions are the right ones for your question: whether to count by address, and whether to drop bots, are decisions, and written down.

Check by hand with the definitions: the bounce rate is the number of visitors with exactly one page view divided by all visitors, and the average pages per visitor is the page views divided by the visitors. A log counts addresses, and many people reach a site through the same mobile network address, so the true number of people is uncertain, perhaps higher, which is why analytics tools use cookies or other signals, and why a log is a floor and not an exact count.

Know what your numbers mean

Page views, visits, visitors and users are different things, and two tools can report different figures for the same traffic. Read the definitions of the tool you use, and compare like with like.

Ask a question first

“How many people looked at the delivery page after the candle page?” is better than staring at dashboards. Choose two or three questions that lead to an action, and track only those.

About this course

Builders, plans and prices change often, so the lessons use generic labels such as Builder A and describe categories of tools, and you must check each vendor’s current website for features, prices and limits. Every calculation and check in this lesson was run while the course was written, in Python 3.13 or Node.js 22, on sample data that the lesson provides, with a second independent calculation. The log in this lesson is generated and synthetic. Real analytics must respect privacy law: IP addresses can be personal data, and cookie rules apply to many tools. Check the rules that apply to you.

Practice

Find the busiest hour in the log with awk. Count how many visitors came from the search referrer and viewed more than two pages. List every address that made over 50 requests, and decide whether it is a bot.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What is a page view?

  1. One request for a page
  2. One visitor
  3. One image
  4. One session

A reload counts again.

Why exclude bots from visitor counts?

  1. They use too much space
  2. They are illegal
  3. They are faster
  4. They are not customers and distort the numbers

Crawlers and scanners.

What is a bounce?

  1. A broken link
  2. A page error
  3. A slow page
  4. A visit with a single page view

Not necessarily bad.

Why compare awk and Python?

  1. To make it slower
  2. They give different answers
  3. An independent check of the parsing and the counts
  4. It is required

Same file, different tools.

What does a log count by address approximate?

  1. Exact people
  2. Customers only
  3. Visitors, imperfectly
  4. Purchases

Shared and changing addresses.

Summary

  • A server log records every request; decide what to count.
  • Page views, visitors, sessions and bounces are different measures.
  • Remove bots and non-page requests.
  • Verify counts with an independent tool.

Next lesson

Lesson 9 covers accessibility and the legal basics of a site.

Questions

Do I need Google Analytics or similar?

Not necessarily. Many builders have basic built-in analytics, and privacy-friendly tools exist. Choose by the questions you need answered and the privacy rules that apply, and check current offerings.

What are cookies in analytics?

Small pieces of data stored in the browser that let a tool recognise a returning visitor. Many places require consent for them, so check the rules.

How often should I look?

Weekly or monthly is enough for a small site, with a question in mind. Daily checking of tiny numbers is mostly noise.

Progress is saved in this browser.