Access Log Health Report with Strict Line Validation
StringsAuto-graded · 25 test casesLast updated
Validate access-log lines field by field, then count client errors, server errors, invalid lines and the failure percentage over the valid lines only.
Access Log Health Report
You are given a list of raw web-server log lines. Check each line, then build a summary report from the lines that pass.
Line format
<ip_address> <timestamp> <path> <status_code>
When is a line valid?
Apply the checks below to each line in order. A line is valid only if it passes all of them. Otherwise it is invalid. Never guess or repair missing fields.
- Field count. Split the line on runs of whitespace, exactly like Python's
line.split()with no arguments. Leading and trailing whitespace is ignored, and any whitespace character (spaces, tabs, and so on) separates fields. The line must produce exactly four fields, in the orderip_address,timestamp,path,status_code. - IP address. The
ip_addressfield must be accepted by Python'sipaddress.ip_address(...), which covers IPv4 and IPv6. If it raisesValueError, the line is invalid. - Timestamp. Take the
timestampfield and replace everyZcharacter with+00:00. The result must be accepted by Python'sdatetime.fromisoformat(...), which means it must not raiseValueError. This is the only timestamp rule. Do not apply any extra or stricter RFC 3339 rule. Anythingfromisoformataccepts is valid, even a timestamp without a UTC offset. Anything it rejects is invalid, such as an impossible date, a lowercasezsuffix, or a seconds value of60. - Path. The
pathfield must start with the character/. - Status code. The
status_codefield must be exactly 3 characters long, andstr.isdigit()must be true for it. Its integer value, as converted byint(...), must lie between100and599inclusive. If the conversion fails, the line is invalid. A status with a numeric prefix followed by other characters (for example200abc) is invalid because of the length and digit rules.
Metrics
Compute everything from valid lines only. Invalid lines never enter any count or denominator, except invalid_lines.
total_requests: number of valid lines.client_errors: valid lines whose status is in400to499.server_errors: valid lines whose status is in500to599.failed_requests:client_errors + server_errors.failure_percent:100 * failed_requests / total_requestsusing ordinary true division, with no rounding. Iftotal_requestsis0, it is the integer0.invalid_lines: number of lines that are not valid.
Every line is either valid or invalid, so total_requests + invalid_lines equals the number of input lines.
Output
Return a dictionary with exactly these keys: total_requests, client_errors, server_errors, failed_requests, failure_percent, invalid_lines.
Constraints
0 <= len(entries) <= 10^5- Each line is a string of at most a few hundred characters.
- Statuses
100to399are valid and count as successful (neither client nor server error). - Boundary values
399,400,499,500,599must be classified exactly as described above. - Valid lines may mix IPv4 and IPv6 addresses.
- An empty input list gives all counters
0andfailure_percent0.
Examples
Example 1
Input: build_log_report(['192.168.1.10 2024-01-01T12:00:00Z /home 200', '2001:db8::1 2024-01-01T12:00:01+00:00 /missing 404', '192.168.1.11 2024-01-01T12:00:02Z /error 500'])
Output: {'total_requests': 3, 'client_errors': 1, 'server_errors': 1, 'failed_requests': 2, 'failure_percent': 66.66666666666667, 'invalid_lines': 0}
Example 2
Input: build_log_report(['127.0.0.1 2023-03-12T09:30:00.123Z /ok 399', '::1 2023-03-12T09:30:00-05:00 /bad 400', '127.0.0.1 2023-03-12T09:30:00Z /gone 499', '127.0.0.1 2023-03-12T09:30:00Z /oops 500', '127.0.0.1 2023-03-12T09:30:00Z /fatal 599'])
Output: {'total_requests': 5, 'client_errors': 2, 'server_errors': 2, 'failed_requests': 4, 'failure_percent': 80, 'invalid_lines': 0}
Example 3
Input: build_log_report([])
Output: {'total_requests': 0, 'client_errors': 0, 'server_errors': 0, 'failed_requests': 0, 'failure_percent': 0, 'invalid_lines': 0}
Hints
Hint 1
Handle each line independently: call split() with no arguments, reject the line unless there are exactly four fields, and only then unpack them.
Hint 2
Let the standard library do the hard checks: ipaddress.ip_address for the IP, and datetime.fromisoformat on the timestamp after replacing every 'Z' with '+00:00'. Treat ValueError as 'invalid line' and add no extra timestamp rules.
Hint 3
Check the status as a string first (length 3 and isdigit()), then convert and check the 100 to 599 range. Only after every check passes should you count the line as valid. Compute the percentage at the end with a zero guard.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Handle the lines one at a time, in two stages.
-
Validate the line. Split it with
str.split()(any whitespace, runs collapsed) and require exactly four fields. Then check each field in turn:- The IP goes through
ipaddress.ip_address, which accepts IPv4 and IPv6 and raisesValueErrorotherwise. - The timestamp has every
Zreplaced by+00:00and is passed todatetime.fromisoformat. AValueErrormeans the line is invalid. No other timestamp rule is applied, so the library's definition of a valid timestamp is the definition used here. - The path must start with
/. - The status must be a 3-character string that satisfies
isdigit(), so something like200abcor20is rejected. After conversion it must lie in100..599.
If any check fails, increment
invalid_linesand move on. Nothing else is counted for that line. - The IP goes through
-
Count the line. A line that passes every check increments
total_requests. It then incrementsclient_errorsif the status is in400..499, orserver_errorsif it is in500..599. Statuses below400count only toward the total.
After the loop, failed_requests is the sum of the two error counters, and failure_percent is 100 * failed / total (unrounded), or 0 when there are no valid lines.
Why it is correct
- Counters are touched only after all validation passes, so invalid lines never affect the denominator or the error counts.
- The two status ranges do not overlap, so no request is counted twice.
- The zero guard defines the empty-valid-set case and avoids division by zero.
- Checking the field count before unpacking prevents unpack errors on short or long lines.
- Delegating IP and timestamp validation to the standard library means the validity rules are exactly those the statement names.
Complexity
- Time: O(total characters across all lines), since each line is split and each field is checked once.
- Space: O(1) beyond the input, because only a few counters are kept. The same loop works on a stream of lines without storing them.
Reference solution
from typing import List, Dict, Union
from ipaddress import ip_address
from datetime import datetime
def build_log_report(entries: List[str]) -> Dict[str, Union[int, float]]:
total_requests = 0
client_errors = 0
server_errors = 0
invalid_lines = 0
for line in entries:
fields = line.split()
if len(fields) != 4:
invalid_lines += 1
continue
ip_str, ts_str, path, status_str = fields
try:
ip_address(ip_str)
except ValueError:
invalid_lines += 1
continue
try:
datetime.fromisoformat(ts_str.replace('Z', '+00:00'))
except ValueError:
invalid_lines += 1
continue
if not path.startswith('/'):
invalid_lines += 1
continue
if len(status_str) != 3 or not status_str.isdigit():
invalid_lines += 1
continue
try:
status = int(status_str)
except ValueError:
invalid_lines += 1
continue
if not (100 <= status <= 599):
invalid_lines += 1
continue
total_requests += 1
if 400 <= status <= 499:
client_errors += 1
elif 500 <= status <= 599:
server_errors += 1
failed_requests = client_errors + server_errors
failure_percent = (100 * failed_requests / total_requests) if total_requests > 0 else 0
return {
"total_requests": total_requests,
"client_errors": client_errors,
"server_errors": server_errors,
"failed_requests": failed_requests,
"failure_percent": failure_percent,
"invalid_lines": invalid_lines,
}