Tracing
Tracing writes messages about what a program does, for the person who looks for a problem. The program sends its messages to Trace, and listeners decide where they go: memory, a file, a window. This lesson adds listeners, indents messages, writes messages on a condition and removes a listener.
What you will learn#
Trace.WriteLineand the listeners ofTrace,- a listener that collects messages in memory (
StringWriter) and one that writes a file, IndentandUnindent,WriteLineIfand a category,- adding and removing listeners without changing the code that writes messages,
- how tracing differs from logging.
The tutorial Logging wrote a log that the program owns. Tracing is for diagnosis: the program sends messages to a standard place, and what happens to them is decided outside the code that writes them.
The program#
# tracing - Trace and listeners: messages with an indent, a listener that collects them in memory, a listener that writes a file, and levels
load "dotnet.ring"
using {
"System"
"System.IO"
"System.Diagnostics"
"System.Threading.Tasks"
}
func main
# TRACING writes messages about what a program does, for the person who looks for a problem. A program sends a message to the class
# Trace, and the LISTENERS that were added to Trace decide where it goes: the console, a file, a window, a log service. The program
# that writes the messages does not know where they go, and a listener can be added or removed without changing the code.
oTrace = new Trace()
# 1. A listener that writes into memory: a TextWriterTraceListener on a StringWriter. (A StringWriter is a text writer that keeps
# its text in memory; the tutorial about text readers and writers uses it.)
oWriter = new StringWriter()
oTrace.Listeners.Add((new TextWriterTraceListener).@New(oWriter))
oTrace.AutoFlush = True # write each message at once
oTrace.WriteLine("program started")
oTrace.WriteLine("reading the settings")
? "1. the memory listener has:"
showLines(oWriter.ToString())
# 2. Indent: the messages of a step are pushed to the right, so that a long trace shows the structure of the work
oWriter.GetStringBuilder().Clear()
oTrace.WriteLine("checking the files")
oTrace.Indent()
oTrace.WriteLine("a.txt: ok")
oTrace.WriteLine("b.txt: missing")
oTrace.Indent()
oTrace.WriteLine("tried the backup folder")
oTrace.Unindent()
oTrace.Unindent()
oTrace.WriteLine("done")
? nl + "2. with Indent and Unindent:"
showLines(oWriter.ToString())
# 3. WriteLineIf: the message is written only when a condition is true, and a category can come in front of it
oWriter.GetStringBuilder().Clear()
for nSize in [ 10, 5000, 90000 ]
oTrace.WriteLineIf([ :condition = (nSize > 1000), :message = "the file is big: " + nSize + " bytes" ])
next
oTrace.WriteLine([ :message = "slow query", :category = "database" ])
? nl + "3. WriteLineIf and a category:"
showLines(oWriter.ToString())
# 4. A second listener, on a file: now each message goes to two places. The file keeps the trace after the program ended.
oPath = new Path()
cFile = oPath.Combine([ oPath.GetTempPath(), "ringdotnet-trace-" + oPath.GetRandomFileName() + ".log" ])
oFileListener = (new TextWriterTraceListener).@New(cFile)
oTrace.Listeners.Add(oFileListener)
oWriter.GetStringBuilder().Clear()
oTrace.WriteLine("one message, two listeners")
oTrace.Flush()
? nl + "4. the same message in memory and in the file:"
? " memory: " + oneLine(oWriter.ToString())
oFileListener.Flush()
oFileListener.Dispose()
? " file: " + oneLine(readText(cFile))
# 5. Removing a listener: the messages stop going to it
oTrace.Listeners.Remove(oFileListener)
new File().Delete(cFile)
oWriter.GetStringBuilder().Clear()
oTrace.WriteLine("after the file listener was removed")
? nl + "5. the memory listener still gets messages: " + yesNo(len(oneLine(oWriter.ToString())) > 0)
# 6. A trace with the time of each step: tracing is most useful when the messages say how long something took
oWatch = new Stopwatch()
oWatch.Start()
oWriter.GetStringBuilder().Clear()
oTrace.WriteLine("step 1 started")
new Task().Delay(150).Wait(NULL)
oTrace.WriteLine("step 2: after the pause, at least 100 ms: " + yesNo(oWatch.ElapsedMilliseconds >= 100))
? nl + "6. messages with the time:"
showLines(oWriter.ToString())
# the lines of a text, each one indented by three spaces (the trace output has the line ending of the system)
func showLines cText
aLines = str2list(substr(cText,char(13),""))
for cLine in aLines
if cLine != ""
? " [" + cLine + "]"
ok
next
# a text without its line ending (the trace adds one after each message)
func oneLine cText
return trim(substr(substr(cText,char(13),""),nl,""))
func readText cFile
return new File().ReadAllText(cFile)
func yesNo lValue
if lValue
return "yes"
ok
return "no"1. the memory listener has:
[program started]
[reading the settings]
2. with Indent and Unindent:
[checking the files]
[ a.txt: ok]
[ b.txt: missing]
[ tried the backup folder]
[done]
3. WriteLineIf and a category:
[the file is big: 5000 bytes]
[the file is big: 90000 bytes]
[database: slow query]
4. the same message in memory and in the file:
memory: one message, two listeners
file: one message, two listeners
5. the memory listener still gets messages: yes
6. messages with the time:
[step 1 started]
[step 2: after the pause, at least 100 ms: yes]This program uses a generic function (dnNew) where a class cannot be used. The lesson The generic functions explains them.
How it works#
Trace and listeners#
Trace is a static class, so its members are called through new Trace(): oTrace.WriteLine(text) sends a message to every listener in oTrace.Listeners. A TextWriterTraceListener writes into any text writer: a StringWriter (memory), a file or the console. The listener is added with Listeners.Add(listener). AutoFlush = True makes each message go to the listeners at once; without it messages wait in a buffer until Flush or the end of the program.
Memory and files#
The memory listener is the best choice for a test, because the test can read the messages back: oWriter.ToString() is everything that was traced. A listener made from a file name writes the file; the program flushes and disposes it before reading the file.
Indent#
Indent() pushes the following messages four spaces to the right and Unindent() takes them back. A function that traces what it does indents on entry and unindents on exit, and the trace shows the structure of the calls like an outline.
Conditions and categories#
WriteLineIf([ :condition = ..., :message = ... ]) writes the message only when the condition is true, so a program does not need an if around each message. A second value is a category: WriteLine([ :message = "slow query", :category = "database" ]) writes database: slow query, and a listener or a reader can filter on the category.
Many listeners#
One message went to the memory listener and to the file. Removing a listener (Listeners.Remove) stops the messages going to it, and the program that writes the messages did not change. This is the reason to use Trace for diagnosis: a developer adds a file listener when there is a problem, and the code stays as it is.
Time#
A trace is most useful when the messages say how long something took. The program takes a Stopwatch and uses ElapsedMilliseconds in the messages (the exact number differs on each run, so the program prints a yes or no about it).
A new program has only the default listener, which writes to an attached debugger, so the messages do not appear on the screen until a listener is added (a ConsoleTraceListener, for example). The class Debug has the same members as Trace, but C# compilers remove its calls from release builds; Trace calls stay in every build.
What you learned#
- the listeners of
Traceand where messages go, - memory and file listeners,
- indented messages, conditions and categories,
- adding and removing listeners without changing the code.
Exercises#
- Write a function
traced(name, code)that writesenter name, runs the code, and writesleave namewith the time, withIndentandUnindentaround it. - Add a
ConsoleTraceListenerand look at the messages on the screen. - Write each message with the date and time in front of it.
- Make the file listener append to a file, run the program twice, and read the file.