Search RU
Tasks / Logs / Parsing an nginx combined log line
Statement easy

Parsing an nginx combined log line

Implement `parse_nginx_line(line)` — a parser for one nginx `combined` log line.

**Example line:**

```
203.0.113.7 - - [10/Oct/2026:13:55:36 +0300] "GET /api/orders?page=2 HTTP/1.1" 200 512 "https://example.com/start" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)"
```

**Result:**

```python
{
"remote_addr": "203.0.113.7",
"time": datetime(2026, 10, 10, 10, 55, 36, tzinfo=UTC),
"method": "GET",
"path": "/api/orders?page=2",
"status": 200,
"bytes": 512,
"referer": "https://example.com/start",
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",
}
```

Rules:

- `time` is an aware `datetime` in UTC; the source format is
`10/Oct/2026:13:55:36 +0300`, and the offset is applied to the moment;
- `method` and `path` come from the request line; the query string is part of
`path`;
- `status` is an integer;
- `bytes` is an integer; `-` means `0`;
- `referer` and `user_agent` are strings as written; `-` means the value is
absent → `None`;
- an empty referer `""` stays an empty string;
- spaces inside `user_agent` are preserved;
- a malformed line (not combined, bad time, non-numeric status or bytes, an
extra or missing fragment) → `None`, without raising;
- a non-string input → `None`.

Hidden tests cover a normal line, a 404, an empty referer, spaces in the
user-agent, timezone offsets, malformed lines, and a wrong input type.

Python
logsnginxparsingregex
solution.py Python 3.14
AI mentor

The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.

Log in and ask
Hints 1 of 3 unlocked · attempts: 0
Hint 1

Can the line be parsed with `line.split()`? What breaks on a user-agent with spaces and on an empty referer? And what does `-` mean in `bytes`, `referer`, and `user_agent`?

Hint 2 — unlocks after 1 attempt
Hint 3 — unlocks after 3 attempts