Thanks to visit codestin.com
Credit goes to lib.rs

1 unstable release

new 0.1.0 Nov 20, 2025

#5 in #grammar-rules

MIT license

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 thiserror and anyhow
  • 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:

  1. Try ISO format first (YYYY-MM-DD)
  2. 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
  3. 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

  1. Timestamp parser

    • Detects format
    • Converts into chrono::NaiveDateTime
  2. Kind parser

    • Reads [INFO], [WARN], [ERROR] etc.
  3. Message parser

    • Consumes text until a key=value token appears
  4. Metadata parser

    • Splits key=value pairs
    • Converts them into a HashMap<String, String>
  5. 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