Problems › JavaScript › monitoring
Count log lines by level
A log summariser reports how many lines came in at each level. The level is the first word on the line, and the file is not always tidy.
- The level is the first whitespace-separated word, reported in upper case.
- Lines that are empty or only whitespace are skipped.
- Levels that never appear are not in the result.
countByLevel(lines: list<string>) → map<string, int>
Where you start
function countByLevel(lines) {
}
Worked examples
| Call | Result |
|---|---|
countByLevel(["ERROR disk full","warn retrying","ERROR timeout"]) | {"ERROR":2,"WARN":1} |
countByLevel(["INFO ok"]) | {"INFO":1} |
countByLevel([""," "]) | {} |
countByLevel(["DEBUG"]) | {"DEBUG":1} |
Hint
Trim the line, take everything up to the first space, upper-case it.
Reference solution in JavaScript
function countByLevel(lines) {
const result = {};
for (const line of lines) {
const t = line.trim();
if (t === "") continue;
const level = t.split(/\s+/)[0].toUpperCase();
result[level] = (result[level] || 0) + 1;
}
return result;
}