easy +8 pts

Parse Apache log line

Extract structured fields from a common Apache access log line using Python.

Write a function `parse_apache_log(line: str) -> dict` that parses a single line from an Apache access log (Combined Log Format) and returns a dictionary with the following keys: - `ip`: the client IP address (string) - `timestamp`: the timestamp string inside the brackets, e.g. `10/Oct/2000:13:55:36 -0700` - `request`: the HTTP request line, e.g. `GET /apache_pb.gif HTTP/1.0` - `status`: the HTTP status code as an integer - `size`: the response size in bytes as an integer, or `0` if the log uses `-` for the size The log format is: ``` IP - - [timestamp] "request" status size ``` For example: ``` 127.0.0.1 - - [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326 ``` Your function must handle exactly this format. You may assume the input is a proper single log line with no extra spaces inside the bracket or quote fields. The size field is always a positive integer or `-`. Return the dictionary as described. Implement the function in the code editor. Do not read from stdin or files; just process the argument.

Constraints

The input line length is at most 2048 characters. The timestamp will always be enclosed in square brackets. The request will always be enclosed in double quotes. The size is either a positive integer or `-`. The status is a three-digit integer.

Example

>>> parse_apache_log('127.0.0.1 - - [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326')
{'ip': '127.0.0.1', 'timestamp': '10/Oct/2000:13:55:36 -0700', 'request': 'GET /apache_pb.gif HTTP/1.0', 'status': 200, 'size': 2326}
>>> parse_apache_log('192.168.1.1 - - [12/Dec/2024:08:00:00 +0000] "POST /api/login HTTP/1.1" 401 -')
{'ip': '192.168.1.1', 'timestamp': '12/Dec/2024:08:00:00 +0000', 'request': 'POST /api/login HTTP/1.1', 'status': 401, 'size': 0}
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Consider using split() to separate the line into parts. The first part is the IP. The timestamp is between the first '[' and next ']'. The request is between the first '"' and the next '"'.
For the size, replace '-' with '0' before converting to int.
You can use a regular expression, but a simple split approach is enough.
The line always has the exact structure: IP - - [timestamp] "request" status size
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.