🎓 A1Learner
🔍
0 of 52 lessons completed

Python Project: A Log Analyser

A log is a file of dated lines. A log analyser reads the log and counts each level.

Write a small log

The program writes four log lines first. The read back shows all four.

with open("app.log", "w") as f:
    f.write("INFO start\nINFO load done\nERROR disk full\nINFO stop\n")

with open("app.log") as f:
    for line in f:
        print(line.strip())

Cut a line into parts

split() cuts the line at the spaces. The first part is the level.

line = "ERROR disk full"
parts = line.split()
print(parts[0])

Count with a dict

get() starts a new level at zero. Each sighting adds one.

levels = ["INFO", "ERROR", "INFO", "WARNING", "INFO"]
counts = {}
for level in levels:
    counts[level] = counts.get(level, 0) + 1
print(counts)

Example

with open("server.log", "w") as f:
    f.write("INFO boot\nINFO user login\nWARNING slow disk\nERROR timeout\nINFO page served\nWARNING low memory\nERROR bad request\nINFO shutdown\n")

counts = {}
with open("server.log") as f:
    for line in f:
        level = line.split()[0]
        counts[level] = counts.get(level, 0) + 1

for level in sorted(counts):
    print(level + ":", counts[level])

Key points

  • Log: a file where each line records one event
  • Level: the tag on a line, like INFO or ERROR
  • Use a dict to count each level
  • Use line.split() to cut a line into parts
  • Use dict.get(level, 0) + 1 to count a level
  • The first part of a line is its level

In this example, the program writes a server log first. The log holds eight lines at three levels. The loop takes each line in turn. split()[0] takes the level from each line. get() counts each level as it appears. The last loop prints the levels in order, with their counts.

Note

A level the code never saw starts at zero.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

How does the analyser count a level it never saw?