ZetCode

Tcl debugging and tracing

last modified November 24, 2026 Tcl 8.6

Tcl does not ship with a symbolic debugger, but the interpreter exposes enough information to find most problems quickly. A value can be printed, the call stack can be inspected, an error can carry its own trace, and variables or commands can be watched while the program runs.

This article covers the tools in the order they are usually reached for: puts, info level and info frame, errorInfo, variable and command traces, timing, parray, bgerror and the interactive tclsh prompt.

Debugging with puts

Printing a value at the point where it is produced is still the fastest way to test an assumption. A small debug procedure with a global flag keeps the messages in the code while allowing them to be switched off, and writing them to stderr keeps the standard output free for real data.

debug.tcl
set ::debug 1

proc debug {msg} {
    if {$::debug} {
        puts "DEBUG: $msg"
    }
}

proc parsePort {text} {
    debug "parsing port from '$text'"
    set port [string trim $text]
    debug "trimmed value is '$port'"
    return $port
}

puts "result: [parsePort { 8080 }]"
set ::debug 0
puts "result: [parsePort { 9090 }]"

With the flag set, the two calls inside parsePort report the input and the trimmed value. After set ::debug 0 the same procedure runs silently. In a script whose standard output is parsed by another program, use puts stderr instead, or open a log channel.

$ tclsh debug.tcl
DEBUG: parsing port from ' 8080 '
DEBUG: trimmed value is '8080'
result: 8080
result: 9090

info level and info frame

When a value is wrong deep inside a call chain, the next question is who called whom. info level returns the current depth, and info level N returns the command at level N, where level 1 is the outermost call. info level 0 is the command being evaluated now. info frame returns a dictionary with the type, source line, command, procedure and level of a frame.

levels.tcl
proc showStack {} {
    puts "called as: [info level 0]"
    for {set level [info level]} {$level >= 1} {incr level -1} {
        puts "  level $level: [info level $level]"
    }
    set frame [info frame -1]
    puts "caller: [dict get $frame proc] at line [dict get $frame line]"
}

proc first {x} {
    second $x
}

proc second {x} {
    showStack
}

first 10

The depth is three: showStack, second and first. The loop prints the calls from the innermost to the outermost, and info frame -1 describes the caller, including the procedure name and the line in the source file that made the call.

$ tclsh levels.tcl
called as: showStack
  level 3: showStack
  level 2: second 10
  level 1: first 10
caller: ::second at line 15

errorInfo and errorstack

When a script raises an error, Tcl records both the message and the stack of calls that led to it. The catch command can store the message and an options dictionary with three useful entries: -errorinfo, -errorcode and -errorstack. The stack trace is meant for people, while the error stack is a structured list of token-parameter pairs: CALL records a procedure with its arguments, UP a caller level and INNER the innermost return. The global ::errorInfo holds the formatted trace.

errors.tcl
proc readConfig {file} {
    if {![file exists $file]} {
        error "no such configuration file: $file"
    }
    return [read $file]
}

proc start {} {
    readConfig "missing.conf"
}

if {[catch {start} msg opts]} {
    puts "message:   $msg"
    puts "errorCode: [dict get $opts -errorcode]"
    puts "errorstack: [dict get $opts -errorstack]"
    puts "--- errorInfo ---"
    puts [dict get $opts -errorinfo]
}

The message is the argument of error, and the error code is NONE because the error carries no machine-readable category. The error stack packs the path into one line: the inner return, the failing call and its caller. The formatted trace lists the same calls with the source lines, one invoked from within step at a time. Read it from the bottom up to follow the path that led to the failure.

$ tclsh errors.tcl
message:   no such configuration file: missing.conf
errorCode: NONE
errorstack: INNER {returnImm {no such configuration file: missing.conf} {}} CALL {readConfig missing.conf} CALL start
--- errorInfo ---
no such configuration file: missing.conf
    while executing
"error "no such configuration file: $file""
    (procedure "readConfig" line 3)
    invoked from within
"readConfig "missing.conf""
    (procedure "start" line 2)
    invoked from within
"start"

trace variable

A variable trace calls a procedure whenever a variable is read, written or unset. The handler receives the variable name, the array element name (empty for a scalar) and the operation. Traces are useful for logging configuration changes or for finding the place that modifies a value unexpectedly.

tracevar.tcl
set counter 0

proc logWrite {name index op} {
    upvar #0 $name value
    puts "trace: $name $op -> $value"
}

trace add variable counter write logWrite

set counter 10
incr counter 5

The trace fires after the new value has been stored, so the handler sees 10 and then 15. upvar #0 reaches the global variable from the handler's own scope. A trace is removed with trace remove variable counter write logWrite; the Tcl trace command page lists all operations.

$ tclsh tracevar.tcl
trace: counter write -> 10
trace: counter write -> 15

trace command

An execution trace runs around a command instead of a variable. The enter handler receives the command and the operation, and the leave handler receives the command, the return code, the result and the operation. Wrapping a procedure this way shows every call and every result without editing the procedure itself.

tracecmd.tcl
proc greet {name} {
    return "Hello there, $name!"
}

proc onEnter {command op} {
    puts "enter: $command"
}

proc onLeave {command code result op} {
    puts "leave: $result (code $code)"
}

trace add execution greet enter onEnter
trace add execution greet leave onLeave

puts [greet "Jane"]

trace remove execution greet enter onEnter
trace remove execution greet leave onLeave
puts [greet "Peter"]

The enter line contains the command as it was called, including the argument. The leave line reports the result and a return code of 0, which means normal completion. After the two trace remove calls the second greeting runs without any trace output.

$ tclsh tracecmd.tcl
enter: greet Jane
leave: Hello there, Jane! (code 0)
Hello there, Jane!
Hello there, Peter!

time and repeatable timing

Guessing which loop is slow is unreliable, so measure it. The time script ?count? command evaluates a script several times and returns the average number of microseconds per iteration. A count above one smooths out scheduler noise, and the absolute numbers depend on the machine.

timing.tcl
proc buildList {n} {
    set items {}
    for {set i 0} {$i < $n} {incr i} {
        lappend items [expr {$i * $i}]
    }
    return $items
}

puts "ten runs:   [time {buildList 1000} 10]"
puts "single run: [time {buildList 1000} 1]"

The ten-run average is more stable than a single measurement, which can be disturbed by other processes. Compare two implementations on the same machine and with the same count rather than trusting an isolated number. The Tcl time command page documents the exact format of the result.

$ tclsh timing.tcl
ten runs:   67.2 microseconds per iteration
single run: 53 microseconds per iteration

parray

Arrays are convenient for configuration data and counters, but printing one element at a time is tedious. parray prints every element sorted by key and aligned in columns, which makes a snapshot of an array easy to read while debugging.

parray.tcl
array set config {
    host localhost
    port 8080
    user admin
}

parray config
puts "keys: [lsort [array names config]]"

The keys appear in alphabetical order and the equals signs line up, even though the array was filled in a different order. parray is meant for humans, so do not parse its output; in code use array names, array get or dict instead. The Tcl array command page covers those operations.

$ tclsh parray.tcl
config(host) = localhost
config(port) = 8080
config(user) = admin
keys: host port user

bgerror

An error inside an event callback does not propagate back to the main script. The event loop catches it and calls the bgerror procedure with the error message. The default implementation writes the message and the stack to the error channel; replacing it lets a program log background failures or count them.

bgerror.tcl
proc failLater {} {
    error "failed in the background"
}

proc bgerror {message} {
    puts "bgerror called"
    puts "message: $message"
    puts "first stack line: [lindex [split $::errorInfo \n] 0]"
    set ::done 1
}

after 100 failLater
vwait ::done
puts "main continues"

after schedules failLater, and vwait keeps the event loop running. When the callback fails, Tcl calls bgerror, which prints the message and the first line of ::errorInfo. Setting done ends the wait. In a real program, log the full trace and keep the event loop alive.

$ tclsh bgerror.tcl
bgerror called
message: failed in the background
first stack line: failed in the background
main continues

The interactive tclsh prompt

Running tclsh without a file name starts an interactive session. The % prompt accepts one command at a time, evaluates it and prints its result. A command that spans several lines, such as a procedure definition, continues until the braces balance; tclsh shows no secondary prompt, so the cursor simply waits. Type exit or press Ctrl+D to leave. At startup the interpreter reads ~/.tclshrc, and setting tcl_prompt1 changes the prompt.

$ tclsh
% puts [info patchlevel]
8.6.12
% set name Jane
Jane
% puts "Hello there, $name!"
Hello there, Jane!
% proc square {n} {
    expr {$n * $n}
}
% square 7
49
% exit

Source

The Tcl 8.6 manual documents the introspection, trace and error commands used in this article. The parray command is described with the other library utilities.

This article moved from simple print statements to stack inspection, error traces, variable and command traces, timing, arrays and background errors. The Tcl info command page covers the remaining introspection subcommands, and Tcl error command explains how to raise and annotate errors.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Tcl Tutorials.