RingDotNetfor Ring

A project: analyze a log file

Put several lessons to work in one useful program — read a text file, take each line apart with a regular expression, count with a dictionary, summarize with LINQ and write a JSON report.

What you will learn#

The task#

A server writes lines like these to a log file:

2024-05-17 08:15:02 ERROR [db] connection lost
2024-05-17 08:16:10 INFO [web] request done

We want to know: how many lines of each level, which parts have errors, which error texts occur, and to save a short report.

The plan#

  1. Read the file line by line.
  2. Cut each line into date, time, level, part, text with a regular expression. Lines that do not match are skipped.
  3. Count with a dictionary: lines per level, errors per part.
  4. Collect the error texts and ask LINQ for the distinct ones, sorted.
  5. Write a JSON report.

The program makes its own sample log first, so that you can run it anywhere.

The program#

samples/UsingDotNet/tutorials/ch05_log_analyzer.ring
# a project - analyze a log file (files, regular expressions, dictionaries, LINQ, JSON)
load "dotnet.ring"

using {
	"System"
	"System.IO"
	"System.Text.RegularExpressions"
	"System.Collections.Generic"
	"System.Linq"
	"System.Text.Json"
}

func main

	# STEP 1. Make a sample log file (a real program would read an existing file)
	cLog = new Path().Combine([new Path().GetTempPath(),"ringdotnet_log_analyzer.log"])
	makeLog(cLog)
	? "STEP 1: log written, " + len(new File().ReadAllLines(cLog).toList()) + " lines"

	# STEP 2. Read it and pick the parts of each line with a regular expression.
	#   a line looks like:  2024-05-17 08:15:02 ERROR [db] connection lost
	oLine = new Regex("^(?<date>\d{4}-\d{2}-\d{2}) (?<time>\d{2}:\d{2}:\d{2}) (?<level>[A-Z]+) \[(?<part>\w+)\] (?<text>.+)$")
	oLevels = new NumberDictionary()          # level -> how many
	oParts = new NumberDictionary()           # part with errors -> how many
	aErrors = []                              # the texts of the errors
	nLines = 0
	aLogLines = new File().ReadAllLines(cLog).toList()
	for cLine in aLogLines
		oMatch = oLine.Match(cLine)
		if not oMatch.Success
			loop
		ok
		nLines++
		cLevel = oMatch.Groups.Item("level").Value
		cPart = oMatch.Groups.Item("part").Value
		oLevels.SetItem(cLevel,count(oLevels,cLevel) + 1)
		if cLevel = "ERROR"
			oParts.SetItem(cPart,count(oParts,cPart) + 1)
			aErrors + oMatch.Groups.Item("text").Value
		ok
	next
	? "STEP 2: " + nLines + " lines understood"

	# STEP 3. Report
	? nl + "STEP 3: lines per level"
	for cLevel in ["INFO","WARN","ERROR"]
		? "   " + cLevel + " : " + count(oLevels,cLevel)
	next
	? "   Errors per part: db=" + count(oParts,"db") + " web=" + count(oParts,"web") + " disk=" + count(oParts,"disk")

	# STEP 4. LINQ: the distinct error texts, sorted
	aDistinct = dnQuery(aErrors).Distinct().OrderBy("xDotNetResult = aDotNetArgs[1]").ToList()
	? nl + "STEP 4: " + len(aDistinct) + " different errors:"
	for cText in aDistinct
		? "   - " + cText
	next

	# STEP 5. Save a JSON report and read it back
	cReport = new Path().Combine([new Path().GetTempPath(),"ringdotnet_log_analyzer-report.json"])
	aReport = [
		["lines",nLines],
		["errors",len(aErrors)],
		["different",len(aDistinct)]
	]
	new File().WriteAllText([ :path = cReport, :contents = webJsonText(aReport) ])
	? nl + "STEP 5: report " + new File().ReadAllText(cReport)
	new File().Delete(cLog)
	new File().Delete(cReport)

# a count from the dictionary (0 when the key is missing)
func count oDictionary, cKey

	aFound = oDictionary.TryGetValue(cKey)
	if aFound[1]
		return aFound[2]
	ok
	return 0

# a small JSON object from [name, value] pairs
func webJsonText aPairs

	cText = "{"
	for nIndex = 1 to len(aPairs)
		if nIndex > 1
			cText += ","
		ok
		cText += '"' + aPairs[nIndex][1] + '":' + aPairs[nIndex][2]
	next
	return cText + "}"

func makeLog cFile

	aLines = []
	aLevels = ["INFO","INFO","WARN","INFO","ERROR","INFO","ERROR","WARN","INFO","ERROR"]
	aParts = ["db","web","disk","web","db","web","disk","db","web","web"]
	aTexts = ["connection lost","request done","slow response","user logged in","connection lost","page served","disk almost full","retrying","cache warmed","timeout"]
	for nIndex = 1 to 30
		nPick = (nIndex - 1) % 10 + 1
		cTime = "08:" + right("0" + (nIndex % 60),2) + ":00"
		aLines + ("2024-05-" + right("0" + (17 + floor(nIndex / 10)),2) + " " + cTime + " " + aLevels[nPick] + " [" + aParts[nPick] + "] " + aTexts[nPick])
	next
	aLines + "this line is not in the format"
	cText = ""
	for cLine in aLines
		cText += cLine + windowsnl()
	next
	new File().WriteAllText([ :path = cFile, :contents = cText ])
Output
STEP 1: log written, 31 lines
STEP 2: 30 lines understood

STEP 3: lines per level
   INFO : 15
   WARN : 6
   ERROR : 9
   Errors per part: db=3 web=3 disk=3

STEP 4: 3 different errors:
   - connection lost
   - disk almost full
   - timeout

STEP 5: report {"lines":30,"errors":9,"different":3}

How it works#

The regular expression#

^(?<date>\d{4}-\d{2}-\d{2}) (?<time>\d{2}:\d{2}:\d{2}) (?<level>[A-Z]+) \[(?<part>\w+)\] (?<text>.+)$

Read it left to right: four digits, a dash, two digits... then a space, a time, a word in capital letters (the level), a word in square brackets (the part), and the rest of the line. (?<level>...) is a named group: after a match, oMatch.Groups.Item("level").Value reads it. oMatch.Success says whether the line matched at all; the last line of the sample file does not, so it is skipped (30 of 31 lines were understood).

Counting with a dictionary#

A dictionary maps a key to a number. To count you read the old value (0 if the key is new), add one and write it back. The helper count(oDictionary, cKey) hides the TryGetValue detail, which returns [found, value].

LINQ#

dnQuery(aErrors).Distinct().OrderBy(...).ToList() removes duplicates and sorts: three different errors out of nine.

The report#

A JSON object is simple text: the helper builds {"lines":30,"errors":9,"different":3}. For real data, JsonSerializer and webJson (the tutorial A web service with a database) do this for you.

Habits that the program shows#

HabitWhere
one function per job (makeLog, count, webJsonText)the bottom of the file
skip bad input instead of crashingif not oMatch.Success loop ok
clean up temporary filesFile.Delete at the end
steps numbered in the outputSTEP 1 ... STEP 5

What you learned#

Exercises#

  1. Count the errors per day: put the date in a dictionary.
  2. Print the busiest hour (use the first two characters of the time).
  3. Take the file name from the command line (sysargv[3]) and report an error if it does not exist.
  4. Write the report with webJson instead of the helper (with "RingDotNet.Web" in the using block).

Next#

A project: find duplicate files

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.