JAVASCRIPT

Parse Structured Log Lines into Key-Value Pairs

Learn to parse structured log entries, like access logs, into easily accessible key-value objects using JavaScript's regex capture groups and `matchAll`.

const logLine = '127.0.0.1 - user [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326';
const logRegex = /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s-\s(\S+)\s\[(.*)\]\s"(\S+)\s(\S+)\s(\S+)"\s(\d{3})\s(\d+)/;
const match = logLine.match(logRegex);

if (match) {
  const parsedLog = {
    ip: match[1],
    user: match[2],
    timestamp: match[3],
    method: match[4],
    path: match[5],
    protocol: match[6],
    status: parseInt(match[7]),
    size: parseInt(match[8])
  };
  console.log(parsedLog);
} else {
  console.log("Log line did not match pattern.");
}
How it works: This JavaScript snippet demonstrates how to parse a common Apache-style log line using a regular expression with capturing groups. Each set of parentheses `()` in the regex captures a specific part of the log (e.g., IP address, user, timestamp, HTTP method). The `match()` method returns an array where each captured group is an element, which is then mapped to a structured object for easy data access and analysis.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs