Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 02 · 50 minutes

Turn three kinds of log into one list of events you can count

After this lesson you can
  • Parse syslog lines and web access lines into events with the same fields
  • Convert every time to UTC, whatever clock the host uses
  • Count events by action and outcome, and report the lines that cannot be read
Lab files of this lesson (6)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

The team lead looked at your notes from lesson 1: "Good. But I cannot sort three files into one story. The ssh log says 13:59 and the web log says 13:01, and I do not know which came first. And your counts skip the broken lines without telling me." You write one program that reads all three logs, gives every line the same fields and the same clock, and says how many lines it could not read.

Recall

Lesson 1: what two things does the time of a syslog line not tell you?

The year and the time zone. A line of auth.log or syslog only has month, day and time on the clock of the host.

Lesson 1: your count of status codes had two empty entries. What were they, and what would a better tool do?

They were broken lines, cut in the middle. A better tool counts them and reports them, so that nobody believes that every line was read.

The idea

An event is one thing that happened, written in the same shape whatever file it came from. Parsing is the step that reads a raw line and finds its parts. Normalising is the step that gives the parts one form: one clock (UTC, the world time that has no daylight saving), one name for each field, and one word for each kind of action. After that you can sort, join and count events from every source with the same code.

From raw lines to events you can count
Raw logslogparse.pyOutputauth.logaccess.logsyslogParserEventevents.jsonlCounts123456Raw logslogparse.pyOutputauth.logaccess.logsyslogParserEventevents.jsonlCounts123456
  1. auth.log → Parser: syslog format
  2. access.log → Parser: combined log format
  3. syslog → Parser: syslog format
  4. Parser → Event: same fields, time in UTC
  5. Event → events.jsonl: one JSON object on each line
  6. events.jsonl → Counts: by action, outcome, user, address

Every event has these fields. A field that a line does not have is None (null in JSON).

FieldMeaning
tsTime in UTC, as text like 2026-11-20T12:59:21Z. Text of this form sorts in time order.
source, host, processWhich file, which machine, which program.
action, outcomeWhat happened (login, request, sudo, user_add, firewall_block, cron_run ...) and how it ended (success, failure).
user, ip, portWho, from where, and the port of a blocked connection.
method, path, status, bytes, agentThe parts of a web request.
msg, refThe message, and the file and line number that it came from, so you can always go back to the raw line.

Worked example

1. See why the clocks matter

The intruder's ssh login and the first admin page after it are in two different files. Search for both by their text.

grep "Accepted password for mwebb from 203" data/auth.log
grep "POST /admin/login" data/access.log | cut -c1-80
Nov 20 13:59:21 web01 sshd[1664]: Accepted password for mwebb from 203.0.113.50 port 38086 ssh2
203.0.113.50 - - [20/Nov/2026:13:01:26 +0000] "POST /admin/login HTTP/1.1" 302 0

Read as plain text, the ssh login (13:59:21) comes after the admin login (13:01:26). That is wrong. The server clock of web01 runs one hour ahead of UTC, and the web server writes UTC. The ssh login is at 12:59:21 UTC, so it came first. Every join of logs must start with one clock.

The same three events on one clock (UTC)
12:59:21ssh login of mwebb (clock 13:59:21)13:01:26POST /admin/login from 203.0.113.5013:03:51customer export, 2.4 MB12:59:21ssh login of mwebb (clock 13:59:21)13:01:26POST /admin/login from 203.0.113.5013:03:51customer export, 2.4 MB

2. Read one syslog line and move its time

datetime makes a date and time, timezone(timedelta(hours=1)) is a clock that runs one hour ahead of UTC, and astimezone converts a time to another clock. re.match cuts the line at a pattern, and groups() returns the parts.

The pattern looks hard, so take it apart. A regular expression is a pattern for text: each part says what to expect at that place, and a part in round brackets is returned by groups(). Four new signs: \w is a letter, a digit or an underscore, \s is a space or a tab, . is any character, and * means any number of the part before it (also none).

Part of the patternWhat it readsIn the example
^(\w{3})start of the line, then three letters: the monthNov
+(\d+)one or more spaces, then digits: the day20
(\d\d:\d\d:\d\d)the time13:59:21
(\S+)any characters that are not spaces: the hostweb01
([^\s\[:]+)characters that are not a space, [ or :: the programsshd
(?:\[(\d+)\])?an optional number in square brackets: the process id ((?: ) groups but does not return)1664
: *(.*)$a colon, spaces, and the rest of the line to the end: the messageAccepted password ...

The code below cuts one line with this pattern and moves its time.

python3 - <<'EOF'
import re
from datetime import datetime, timedelta, timezone

line = "Nov 20 13:59:21 web01 sshd[1664]: Accepted password for mwebb from 203.0.113.50 port 38086 ssh2"
m = re.match(r"^(\w{3}) +(\d+) (\d\d:\d\d:\d\d) (\S+) ([^\s\[:]+)(?:\[(\d+)\])?: *(.*)$", line)
print(m.groups())
local = datetime(2026, 11, 20, 13, 59, 21, tzinfo=timezone(timedelta(hours=1)))
print(local.astimezone(timezone.utc))
EOF
('Nov', '20', '13:59:21', 'web01', 'sshd', '1664', 'Accepted password for mwebb from 203.0.113.50 port 38086 ssh2')
2026-11-20 12:59:21+00:00

The year (2026) is not in the line. The program gets it as an argument. A log that crosses New Year needs more care (Field notes).

3. Read the message

The message of sshd tells what happened, and a second set of patterns finds the user and the address. (?:invalid user )? allows the words invalid user and does not return them. (\S+) returns the user, and a second one the address. The same is done for sudo, useradd, firewall blocks and cron lines (all in the finished file). In parse_syslog, (f := FAILED.search(msg)) stores the result of the search in f and tests it in one step. Each match sets action and outcome; a line that matches nothing keeps the action other but is still an event.

FAILED = re.compile(r"Failed password for (?:invalid user )?(\S+) from (\S+) port")
ACCEPTED = re.compile(r"Accepted (\S+) for (\S+) from (\S+) port")
    ev = event(ts=iso(when), host=m[4], process=process, action="other", msg=msg)
    if process == "sshd" and (f := FAILED.search(msg)):
        ev.update(action="login", outcome="failure", user=f[1], ip=f[2])
    elif process == "sshd" and (a := ACCEPTED.search(msg)):
        ev.update(action="login", outcome="success", user=a[2], ip=a[3])

4. Read a web access line

The access log needs a different pattern. A | means "or": (\d+|-) reads the size, which is digits or a dash when the server sent nothing. [+-]\d{4} reads the offset (+0000). [^"]* reads everything up to the next quotation mark. The program takes the time offset from the line and does not guess. A line that does not fit the pattern is not an event: the parser returns None, and the loader keeps the file name, the line number and the text of every such line.

ACCESS = re.compile(r'^(\S+) \S+ (\S+) \[(\d+)/(\w+)/(\d+):(\d\d:\d\d:\d\d) ([+-]\d{4})\] "(\S+) (\S+) [^"]*" '
                    r'(\d{3}) (\d+|-) "[^"]*" "([^"]*)"$')
    m = ACCESS.match(line)
    if not m or m[4] not in MONTHS:
        return None

The groups are, in order: address, user, day, month, year, time, offset, method, path, status, size and agent.

5. The finished file

Save logparse.py, which holds all the patterns and both parsers. Counter counts items, json.dumps writes a dictionary as one line of JSON, and sources(hours) lists the files of one host with the hours that its clock runs ahead of UTC.

The finished file: logparse.py

logparse.py

"""logparse.py: turn raw log lines into events, and write them as JSON lines.

    python3 logparse.py [folder] [year] [out] [hours]      defaults: data 2026 events.jsonl 1
"""
import json
import re
import sys
from collections import Counter
from datetime import datetime, timedelta, timezone
from pathlib import Path

FIELDS = ("ts", "source", "host", "process", "action", "outcome", "user", "ip", "port", "method", "path",
          "status", "bytes", "agent", "msg", "ref")
MONTHS = {m: i for i, m in enumerate("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(), 1)}

SYSLOG = re.compile(r"^(\w{3}) +(\d+) (\d\d:\d\d:\d\d) (\S+) ([^\s\[:]+)(?:\[(\d+)\])?: *(.*)$")
ACCESS = re.compile(r'^(\S+) \S+ (\S+) \[(\d+)/(\w+)/(\d+):(\d\d:\d\d:\d\d) ([+-]\d{4})\] "(\S+) (\S+) [^"]*" '
                    r'(\d{3}) (\d+|-) "[^"]*" "([^"]*)"$')
FAILED = re.compile(r"Failed password for (?:invalid user )?(\S+) from (\S+) port")
ACCEPTED = re.compile(r"Accepted (\S+) for (\S+) from (\S+) port")
SESSION = re.compile(r"session (opened|closed) for user (\w+)")
SUDO = re.compile(r"(\S+) : TTY=\S+ ; PWD=\S+ ; USER=(\S+) ; COMMAND=(.*)")
USERADD = re.compile(r"new user: name=([^,]+),")
BLOCK = re.compile(r"UFW BLOCK .*SRC=(\S+) .*DPT=(\d+)")
CRON = re.compile(r"\((\S+)\) (CMD|REPLACE)")


def iso(when):
    """A datetime as text in UTC. Text of this form sorts in time order."""
    return when.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def event(**fields):
    """One event: every field is there, and a field that the line does not have is None."""
    return {name: fields.get(name) for name in FIELDS}


def parse_syslog(line, year, hours):
    """One line of auth.log or syslog. The clock of the host runs `hours` ahead of UTC."""
    m = SYSLOG.match(line)
    if not m or m[1] not in MONTHS:
        return None
    zone = timezone(timedelta(hours=hours))
    when = datetime(year, MONTHS[m[1]], int(m[2]), *map(int, m[3].split(":")), tzinfo=zone)
    process, msg = m[5], m[7]
    ev = event(ts=iso(when), host=m[4], process=process, action="other", msg=msg)
    if process == "sshd" and (f := FAILED.search(msg)):
        ev.update(action="login", outcome="failure", user=f[1], ip=f[2])
    elif process == "sshd" and (a := ACCEPTED.search(msg)):
        ev.update(action="login", outcome="success", user=a[2], ip=a[3])
    elif process == "sshd" and (s := SESSION.search(msg)):
        ev.update(action="session", outcome=s[1], user=s[2])
    elif process == "sudo" and (s := SUDO.match(msg)):
        ev.update(action="sudo", user=s[1], msg=s[3])
    elif process == "useradd" and (u := USERADD.search(msg)):
        ev.update(action="user_add", user=u[1])
    elif process == "kernel" and (b := BLOCK.search(msg)):
        ev.update(action="firewall_block", ip=b[1], port=int(b[2]))
    elif process == "CRON" and (c := CRON.match(msg)):
        ev.update(action="cron_run", user=c[1])
    elif process == "crontab" and (c := CRON.match(msg)):
        ev.update(action="cron_edit", user=c[1])
    return ev


def parse_access(line, year=None, hours=None):
    """One line of a web server access log in the combined format. The time carries its own offset."""
    m = ACCESS.match(line)
    if not m or m[4] not in MONTHS:
        return None
    sign = -1 if m[7][0] == "-" else 1
    zone = timezone(sign * timedelta(hours=int(m[7][1:3]), minutes=int(m[7][3:])))
    when = datetime(int(m[5]), MONTHS[m[4]], int(m[3]), *map(int, m[6].split(":")), tzinfo=zone)
    user = None if m[2] == "-" else m[2]
    size = 0 if m[11] == "-" else int(m[11])
    return event(ts=iso(when), process="nginx", action="request", user=user, ip=m[1], method=m[8],
                 path=m[9], status=int(m[10]), bytes=size, agent=m[12])


def sources(hours=1):
    """The files of one host: file, parser, name of the source, hours that the clock of the host runs ahead of UTC."""
    return [("auth.log", parse_syslog, "auth", hours), ("syslog", parse_syslog, "syslog", hours),
            ("access.log", parse_access, "web", 0)]


def load(folder, year, files=None, web_host="web01"):
    """Read the files. Return the events in time order and the lines that no parser could read."""
    events, bad = [], []
    for name, parse, source, hours in files or sources():
        for number, line in enumerate(Path(folder, name).read_text(errors="replace").splitlines(), 1):
            ev = parse(line, year, hours)
            if ev is None:
                bad.append((name, number, line))
                continue
            ev.update(source=source, ref=f"{name}:{number}", host=ev["host"] or web_host)
            events.append(ev)
    events.sort(key=lambda e: e["ts"])
    return events, bad


if __name__ == "__main__":
    folder = sys.argv[1] if len(sys.argv) > 1 else "data"
    year = int(sys.argv[2]) if len(sys.argv) > 2 else 2026
    target = sys.argv[3] if len(sys.argv) > 3 else "events.jsonl"
    events, bad = load(folder, year, sources(int(sys.argv[4]) if len(sys.argv) > 4 else 1))
    with open(target, "w") as out:
        for ev in events:
            out.write(json.dumps(ev) + "\n")
    print(f"{len(events)} events written to {target}, {len(bad)} lines not read")
    for source, count in sorted(Counter(e["source"] for e in events).items()):
        print(f"  source {source:7s} {count:5d}")
    for name, number, line in bad:
        print(f"  not read {name}:{number}: {line[:50]}")

6. Run it

The program takes the folder, the year and the name of the output file.

python3 logparse.py data 2026 events.jsonl
1290 events written to events.jsonl, 3 lines not read
  source auth      181
  source syslog     41
  source web      1068
  not read syslog:21: Nov 20 10:03:12 --- MARK ---
  not read access.log:301: 198.51.100.119 - - [20/Nov/2026:07:16:00 +000
  not read access.log:901: 198.51.100.104 - - [20/Nov/2026:16:58:22 +000

1,290 events are in the file, and three lines were not read: the two cut lines of the access log and the line --- MARK --- of the syslog, which is a marker and not an event. Look at one event. sed -n 1p prints line 1 of the file and nothing else, and grep -m1 stops after the first matching line.

sed -n 1p events.jsonl
grep -m1 '"user_add"' events.jsonl
{"ts": "2026-11-20T00:00:00Z", "source": "web", "host": "web01", "process": "nginx", "action": "request", "outcome": null, "user": null, "ip": "192.0.2.5", "port": null, "method": "GET", "path": "/healthz", "status": 200, "bytes": 2, "agent": "kr-monitor/1.0", "msg": null, "ref": "access.log:1"}
{"ts": "2026-11-20T13:04:22Z", "source": "auth", "host": "web01", "process": "useradd", "action": "user_add", "outcome": null, "user": "svc-update", "ip": null, "port": null, "method": null, "path": null, "status": null, "bytes": null, "agent": null, "msg": "new user: name=svc-update, UID=1010, GID=1010, home=/home/svc-update, shell=/bin/bash", "ref": "auth.log:133"}

7. Count by action and outcome

The short program count_events.py reads the events back and counts the pairs of action and outcome. lambda x: -x[1] is a small function without a name: sorted calls it for each item and sorts by the result, so the biggest count comes first.

count_events.py

import json
from collections import Counter

events = [json.loads(line) for line in open("events.jsonl")]
for (action, outcome), n in sorted(Counter((e["action"], e["outcome"]) for e in events).items(), key=lambda x: -x[1]):
    print(f"{n:5d} {action} {outcome or ''}".rstrip())
python3 count_events.py
 1068 request
   70 login failure
   36 login success
   36 session opened
   36 session closed
   27 cron_run
    8 firewall_block
    5 other
    2 sudo
    1 user_add
    1 cron_edit

Now the order is right. The events of the intruder's address, in UTC, put the ssh login first.

grep -E '"ip": "203.0.113.50"' events.jsonl | grep -E '"outcome": "success"|admin/login' | cut -c1-120
{"ts": "2026-11-20T12:59:21Z", "source": "auth", "host": "web01", "process": "sshd", "action": "login", "outcome": "succ
{"ts": "2026-11-20T13:01:26Z", "source": "web", "host": "web01", "process": "nginx", "action": "request", "outcome": nul

Your turn

The VPN gateway vpn01 has its own log, in a third format. Make it with the generator, then read it. Its clock runs two hours ahead of UTC. Its lines look like this: date, time (no zone), host, then pairs key=value.

A line of vpn.log
2026-11-20 15:12:20date and time, no zonevpn01hostevent=connectwhat happeneduser=mwebbwhosrc=203.0.113.50address outsideassigned=...address inside2026-11-20 15:12:20date and time, no zonevpn01hostevent=connectwhat happeneduser=mwebbwhosrc=203.0.113.50address outsideassigned=...address inside
The finished file: gen_vpn.py

gen_vpn.py

"""gen_vpn.py: write data/vpn.log, the log of the VPN server of Fernwood Press for the same day as day 1.

The clock of vpn01 runs in UTC+02:00 and the lines carry no zone. Run: python3 gen_vpn.py
"""
import random
from pathlib import Path

r = random.Random(11)
rows = []  # (seconds since 00:00 local time, text)
for user, src in [("alice", "198.51.100.121"), ("bob", "198.51.100.122"), ("carol", "203.0.113.123"),
                  ("pdiaz", "198.51.100.125")]:
    start = 8 * 3600 + int(r.random() * 3 * 3600)
    if user == "carol":
        rows.append((start - 20, f"event=auth_fail user={user} src={src} reason=bad_password"))
    rows.append((start, f"event=connect user={user} src={src} assigned=192.0.2.{150 + len(rows)}"))
    rows.append((start + 1800 + int(r.random() * 7200), f"event=disconnect user={user} src={src} bytes={int(r.random() * 9e6)}"))
rows.append((15 * 3600 + 12 * 60 + 20, "event=connect user=mwebb src=203.0.113.50 assigned=192.0.2.160"))
rows.append((15 * 3600 + 38 * 60 + 3, "event=disconnect user=mwebb src=203.0.113.50 bytes=48211093"))
Path("data").mkdir(exist_ok=True)
with open("data/vpn.log", "w") as out:
    for sec, text in sorted(rows):
        out.write(f"2026-11-20 {sec // 3600:02d}:{sec % 3600 // 60:02d}:{sec % 60:02d} vpn01 {text}\n")
print(len(rows), "lines written to data/vpn.log")
python3 gen_vpn.py
11 lines written to data/vpn.log

Write vpn_parse.py with a function parse_vpn(line, hours) that returns an event (use event and iso from logparse.py, so that the fields are the same). Map event=auth_fail to action login and outcome failure, connect to vpn_connect and success, and disconnect to vpn_disconnect and closed. Set source to vpn, process to vpn, user from user= and ip from src=. parse_vpn takes two arguments, not three like the parsers in logparse.py, so it does not go into sources(): call it in a loop over the lines of data/vpn.log. Do not change logparse.py: the later lessons use it as it is. Try it without help first. If a check still fails, a working vpn_parse.py is a lab file in the scenario test (lesson 15).

Check yourself

Why does the program store the time as text like 2026-11-20T12:59:21Z and not as a number?

Text of this fixed form sorts in time order with a plain sort, it is readable, and JSON can hold it. The Z says that it is UTC. A number would also work, but a person could not read it.

Why does the event keep a field ref such as auth.log:128?

So that every alert and every report line can be traced back to the raw line. An analyst or an auditor can open the file at that line and check the claim. Without it the event is an unproven opinion.

A syslog file starts on 30 December and runs into January. You give the parser the year 2026 for the whole file. What is wrong with the lines of January, and how do you fix it?

A syslog line has no year, so the parser gives every line 2026. The January lines belong to 2027. Read the lines in order and add one to the year when the month goes from 12 to 1. The time zone can move a line across the year border too: 00:30 on 1 January on a host one hour ahead of UTC is 23:30 on 31 December in UTC, in the year before.

Field notes

  • Keep the raw line. An event is an interpretation, and a parser can be wrong. Store the original file untouched and the ref in each event, as you did here.
  • Parsers break when a program changes its format after an update. Test each parser on a fixed sample file, and watch the count of unread lines: a sudden rise is the first sign of a changed format.
  • A common vocabulary is the point. Public schemas exist for it, such as the Elastic Common Schema and the OCSF schema. Look at their field names before you invent your own for a real project.
  • Daylight saving time makes one hour twice a year. Servers should log in UTC. If a host cannot, log the offset with the time.
  • A user name that comes from a log is not safe to put into a command or a query. Treat every field as input from an attacker.