Editor

Parse a Web Server Log Line

#307 · Regular expressions · Intermediate · 70 XP · about 15 min

Web servers write one line to a log file for every request they answer. A typical line looks like this:

203.0.113.9 - - [10/Oct/2026:13:55:36 +0000] "GET /index.html HTTP/1.1" 200 2326

Write parse_log_line(line) that pulls the useful parts out of one line and returns them as a dictionary with exactly these five keys, in this order:

  • 'ip': the IP address, a string
  • 'method': the request method, a string such as 'GET'
  • 'path': the requested path, a string
  • 'status': the status code, an int
  • 'bytes': the size of the answer, an int, where - in the log means 0

A valid line is made of these parts, separated by single spaces, with nothing before or after them:

  • An IP address: four groups of 1 to 3 digits, separated by dots.
  • Two fields that are not used here, each one or more characters that are not spaces (often -).
  • A timestamp in square brackets: one or more characters that are not ].
  • The request in double quotes: a method (one or more capital letters A to Z), a space, a path (one or more characters that are not spaces), a space, and a protocol made of HTTP/ followed by one or more digits and dots.
  • A status code of exactly 3 digits.
  • The size: one or more digits, or a single -.

If the line does not follow this layout, return an empty dictionary.

Examples

parse_log_line('203.0.113.9 - - [10/Oct/2026:13:55:36 +0000] "GET /index.html HTTP/1.1" 200 2326')
# returns {'ip': '203.0.113.9', 'method': 'GET', 'path': '/index.html', 'status': 200, 'bytes': 2326}
parse_log_line('198.51.100.23 - alice [11/Oct/2026:08:01:02 +0530] "POST /login?next=/home HTTP/2.0" 302 -')
# returns {'ip': '198.51.100.23', 'method': 'POST', 'path': '/login?next=/home', 'status': 302, 'bytes': 0}
parse_log_line('not a log line')
# returns {}

Constraints

  • line has at most 2,000 characters, all ASCII, and no line break.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.