1 unstable release
| new 0.1.0 | Nov 20, 2025 |
|---|
#5 in #grammar-rules
11KB
141 lines
time-parser
time-parser is a Rust command-line tool and library for parsing timestamped log lines.
It automatically detects multiple timestamp formats and converts logs into structured data.
This project was created as a parsing assignment and demonstrates:
- Manual parsing without external parsing frameworks
- Grammar rule design
- Error handling with
thiserrorandanyhow - Full CLI + library separation
- Automated testing and formatting
🧠 Supported Timestamp Formats
The parser automatically detects and supports three formats:
| ISO | 2024-03-15 12:00:00 |
| European | 15-03-2024 12:00:00 |
| American | 03-15-2024 12:00:00 |
Detection logic:
- Try ISO format first (
YYYY-MM-DD) - If that fails:
- If first number > 12 → European (
DD-MM-YYYY) - If second number > 12 → American (
MM-DD-YYYY) - If both ≤ 12 → default to European
- If first number > 12 → European (
- If all fail → error
📜 Log Format Overview
Each log line must follow this structure:
TIMESTAMP [KIND] MESSAGE METADATA
makefile Copy code
Example:
15-03-2024 10:00:00 [INFO] Server started user=alice id=42
yaml Copy code
📏 Grammar Rules
Formal grammar (EBNF-style):
LOG = TIMESTAMP " [" KIND "] " MESSAGE (" " METADATA)? TIMESTAMP = ISO | EU | US ISO = YYYY "-" MM "-" DD " " HH ":" MM ":" SS EU = DD "-" MM "-" YYYY " " HH ":" MM ":" SS US = MM "-" DD "-" YYYY " " HH ":" MM ":" SS
KIND = uppercase_text MESSAGE = text until metadata starts METADATA = KVPAIR ( " " KVPAIR )* KVPAIR = KEY "=" VALUE
markdown Copy code
⚙️ How the Parser Works
-
Timestamp parser
- Detects format
- Converts into
chrono::NaiveDateTime
-
Kind parser
- Reads
[INFO],[WARN],[ERROR]etc.
- Reads
-
Message parser
- Consumes text until a
key=valuetoken appears
- Consumes text until a
-
Metadata parser
- Splits key=value pairs
- Converts them into a
HashMap<String, String>
-
Final output Each line becomes this Rust struct:
pub struct Entry {
pub timestamp: NaiveDateTime,
pub kind: String,
pub message: String,
pub metadata: HashMap<String, String>,
}
💻 CLI Usage
Parse a file:
bash
Copy code
time-parser parse logs.txt
Show credits:
bash
Copy code
time-parser credits
Show help:
bash
Copy code
time-parser --help
Output example:
json
Copy code
{
"timestamp": "2024-03-15 10:00:00",
"kind": "INFO",
"message": "Server started",
"metadata": {
"user": "alice",
"id": "42"
}
}
Dependencies
~2.5–4MB
~70K SLoC