← Back to all snippets
JAVASCRIPT

Extract Specific Data from Log or Config Lines

Learn how to use Regex to efficiently parse and extract specific key-value pairs or data points from structured log entries or configuration files in JavaScript.

function extractLogDetails(logLine) {
    const regex = /^[\[](\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})][\[]([A-Z]+)][:] (.*)$/;
    const match = logLine.match(regex);
    if (match) {
        return {
            timestamp: match[1],
            level: match[2],
            message: match[3]
        };
    }
    return null;
}

const logEntry = "[2023-10-27 10:30:15] [INFO]: User 'john.doe' logged in successfully.";
const details = extractLogDetails(logEntry);
console.log(details);
// Expected Output: { timestamp: '2023-10-27 10:30:15', level: 'INFO', message: "User 'john.doe' logged in successfully." }
How it works: This JavaScript function utilizes a regular expression to parse structured log lines. It defines capture groups `(...)` to extract the timestamp, log level (e.g., INFO, ERROR), and the actual message. The `match()` method returns an array containing the full match and then each captured group, allowing easy access to specific data points.

Need help integrating this into your project?

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

Hire DigitalCodeLabs