Validating Log Records With Line Numbers

Parse timestamped log lines with enumerate so every validation error reports the exact source line instead of a bare message.

RustData Integrity

Code

rustsnippet
54 lines
#[derive(Debug)]
struct Record {
    level: String,
    message: String,
}

// 携带行号的错误:调用方一眼定位到坏数据
#[derive(Debug)]
struct ParseError {
    line: usize,
    reason: String,
}

fn parse_log(text: &str) -> Result<Vec<Record>, ParseError> {
    let mut records = Vec::new();
    for (index, raw) in text.lines().enumerate() {
        let line_no = index + 1; // 行号从 1 起算
        let line = raw.trim();
        if line.is_empty() || line.starts_with('#') {
            continue; // 注释与空行静默跳过
        }
        let (level, message) = line
            .split_once(' ')
            .ok_or_else(|| ParseError {
                line: line_no,
                reason: format!("expected 'LEVEL message', got {raw:?}"),
            })?;
        match level {
            "INFO" | "WARN" | "ERROR" => records.push(Record {
                level: level.to_string(),
                message: message.to_string(),
            }),
            other => {
                return Err(ParseError {
                    line: line_no,
                    reason: format!("unknown level {other:?}"),
                });
            }
        }
    }
    Ok(records)
}

fn main() {
    let log = "# session start\nINFO boot ok\n\nWARN disk 90%\nTRACE missed\n";
    match parse_log(log) {
        Ok(records) => {
            for record in &records {
                println!("{record:?}");
            }
        }
        Err(e) => println!("line {}: {}", e.line, e.reason),
    }
}

How it works

Validating Log Records With Line Numbers comes down to the functions parse_log and main.

A single loop drives the file — for (index, raw) in text.lines().enumerate(). Fallible operations return Result, and the ? operator short-circuits errors up to the caller. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.
  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Using it

Signature: fn parse_log(text: &str) -> Result<Vec<Record>, ParseError>

Running the file prints labeled results such as line — each operation’s effect is visible in the output.

Running the file executes main, which drives parse_log in order.

Key statements

return Err(ParseError {
line: line_no,
reason: format!("unknown level {other:?}"),
});
Ok(records) => {
for record in &records {
println!("{record:?}");
}
}
"INFO" | "WARN" | "ERROR" => records.push(Record {
level: level.to_string(),
message: message.to_string(),
}),

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
No panics — `Result` values carry the failure, and `?` forwards them to the caller.
What does Validating Log Records With Line Numbers print when run?
Running the file directly is enough — expect labeled output lines such as `line`.