Skip to content

Checkpoint: Log Analysis

The Course
•
30 min study

Here's a typical job for LINQ: text comes in, you parse it into records, and you answer questions. Parsing is the hard part, and the queries become short once the data is typed. This checkpoint shows that pattern, which you'll also use in the tracker's reports.

Warm up: parse, then query

SelectMany flattens: each input becomes zero or more outputs. Here it lets a parser drop bad lines without any special case. Predict the output. Note that the bad line just disappears.

Bad lines fall out C#
string[] lines = { "1 ok", "oops", "2 ok" };

var numbers = lines.SelectMany(line =>
{
    string[] parts = line.Split(' ');
    return int.TryParse(parts[0], out int number) ? new[] { number } : Array.Empty<int>();
});

Console.WriteLine(string.Join(",", numbers));
Console.WriteLine(numbers.Sum());
Check your prediction
Text
1,2
3

Passing a question as a lambda

Questions often share their shape, such as "what's the count per something?" A generic helper with a Func for the key removes the repetition, and here it also sorts so the output is stable.

One helper, two questions C#
var requests = new[] { new Request("/", 200), new Request("/a", 404), new Request("/", 200) };

Show(CountBy(requests, request => request.Path));
Show(CountBy(requests, request => request.Status));

static List<(TKey Key, int Count)> CountBy<T, TKey>(IEnumerable<T> items, Func<T, TKey> key)
{
    return items.GroupBy(key)
        .Select(group => (group.Key, group.Count()))
        .OrderByDescending(pair => pair.Item2)
        .ToList();
}

static void Show<TKey>(List<(TKey Key, int Count)> rows)
{
    Console.WriteLine(string.Join(", ", rows.Select(row => $"{row.Key}={row.Count}")));
}

record Request(string Path, int Status);
Check your prediction
Text
/=2, /a=1
200=2, 404=1

Fix it: A message cut short

Each log line is a level, a space, and a message that may contain spaces itself. Predict the output, then run it.

A message cut short C#
string line = "ERROR disk full on /data";
string[] parts = line.Split(' ');
Console.WriteLine($"level: {parts[0]}");
Console.WriteLine($"message: {parts[1]}");
Check your prediction
Text
level: ERROR
message: disk

Split(' ') breaks at every space, so the message is spread over four parts, and parts[1] holds only its first word. Fix it so the whole message survives.

Fix it

Tell Split to stop after two parts. The second part is then everything after the first space:

C#
string line = "ERROR disk full on /data";
string[] parts = line.Split(' ', 2);
Console.WriteLine($"level: {parts[0]}");
Console.WriteLine($"message: {parts[1]}");
Text
level: ERROR
message: disk full on /data

A line with no space at all still gives only one part, so check parts.Length == 2 before reading parts[1]. That's the "bad line" case in the exercise below.

Build it yourself

Exercise

Analyze a server log

Each input line is level minutes message: for example, ERROR 12 disk full. The level is INFO, WARN or ERROR, minutes is a whole number from 0 up, and the message can contain spaces. Parse with a static method that returns a LogLine record or null, and count lines that don't parse.

Then print:

  1. The count at each level, most common first with ties in name order, as WARN: 2.
  2. The first error's message, or no errors.
  3. Distinct error messages, sorted, joined with ; .
  4. The number of bad lines.

When it works, it prints:

Text
ERROR: 3
WARN: 2
INFO: 1
disk full
disk full; lost network
Bad lines: 2
Your workspace C#
#nullable enable

string? line = Console.ReadLine();
Console.WriteLine(line);
INFO 1 started WARN 4 disk low ERROR 9 disk full not a line WARN 11 disk low ERROR 12 disk full ERROR 15 lost network INFO x bad minutes
Hint 1: the idea

Read all the lines first, then parse them into a list of records. After that, each question is one short query, and none of them needs to know about text.

Hint 2: a first step

Split(' ', 3) keeps message spaces together. Write and try the parser before you write any query. Check the level against an array of the three allowed names.

Show one solution
C#
#nullable enable

var lines = new List<string>();
string? input;
while ((input = Console.ReadLine()) is not null)
{
    lines.Add(input);
}

List<LogLine?> parsed = lines.Select(LogLine.Parse).ToList();
List<LogLine> good = parsed.OfType<LogLine>().ToList();

var counts = good.GroupBy(log => log.Level)
    .OrderByDescending(group => group.Count())
    .ThenBy(group => group.Key);
foreach (var group in counts)
{
    Console.WriteLine($"{group.Key}: {group.Count()}");
}

var errors = good.Where(log => log.Level == "ERROR").ToList();
Console.WriteLine(errors.FirstOrDefault()?.Message ?? "no errors");
Console.WriteLine(string.Join("; ", errors.Select(log => log.Message).Distinct().Order()));
Console.WriteLine($"Bad lines: {parsed.Count - good.Count}");

record LogLine(string Level, int Minutes, string Message)
{
    private static readonly string[] Levels = { "INFO", "WARN", "ERROR" };

    public static LogLine? Parse(string line)
    {
        string[] parts = line.Split(' ', 3);
        if (parts.Length != 3 || !Levels.Contains(parts[0]))
        {
            return null;
        }
        if (!int.TryParse(parts[1], out int minutes) || minutes < 0)
        {
            return null;
        }
        return new LogLine(parts[0], minutes, parts[2]);
    }
}
Text
ERROR: 3
WARN: 2
INFO: 1
disk full
disk full; lost network
Bad lines: 2

Parsing and analysis are separate stages. Parse turns each line into a LogLine or null, and every later query works on the clean good list, so none of them has to worry about bad input. Keeping parsed as well makes the bad-line count a subtraction. Split(' ', 3) keeps a message with spaces in one piece, and Distinct().Order() makes the error list the same whatever order the lines arrived in.

OfType<LogLine>() keeps items of that type, which also drops nulls. lines.Select(LogLine.Parse) passes the method directly, as you did with a delegate at the start of today. Could you add a report of the busiest ten-minute window? Try GroupBy(log => log.Minutes / 10).

Was this article helpful?

Your response is saved on this device.