logger(3tcl)

πŸ“¦
version 2.0 Β· 2 versions
, in debian trixie, ubuntu questing, ubuntu resolute, ubuntu stonking

πŸ’– logger πŸ’–

okay bestie, this is the manual page for logger β€” the Object Oriented logging facility, from the 3tcl manual. it's a lot, but we're gonna get through it together. no cap. 🫢


✨ NAME ✨

logger β€” a whole system to control logging of events. that's it. that's the name. iconic. πŸ’…


🌸 SYNOPSIS 🌸

package require Tcl 8.5 9

package require logger ?0.9.5?

logger::init service

logger::import  ?-all?  ?-force? ?-prefix prefix? ?-namespace namespace?
service

logger::initNamespace ns ?level?

logger::services

logger::enable level

logger::disable level

logger::setlevel level

logger::levels

logger::servicecmd service

${log}::debug message

${log}::info message

${log}::notice message

${log}::warn message

${log}::error message

${log}::critical message

${log}::alert message

${log}::emergency message

${log}::setlevel level

${log}::enable level

${log}::disable level

${log}::lvlchangeproc command

${log}::lvlchangeproc

${log}::logproc level

${log}::logproc level command

${log}::logproc level argname body

${log}::services

${log}::servicename

${log}::currentloglevel

${log}::delproc command

${log}::delproc

${log}::delete

${log}::trace command

${log}::trace on

${log}::trace off

${log}::trace status ?procName? ?...?

${log}::trace add procName ?...?

${log}::trace add ?-ns? nsName ?...?

${log}::trace remove procName ?...?

${log}::trace remove ?-ns? nsName ?...?

πŸ¦‹ DESCRIPTION πŸ¦‹

so the logger package gives you a flexible system for logging messages from different services, at priority levels, with different commands. it's giving infrastructure. it's giving main character energy for your logs. ✨

to begin using the logger package, we do the following:

package require logger
set log [logger::init myservice]
${log}::notice "Initialized myservice logging"

... code ...

${log}::notice "Ending myservice logging"
${log}::delete

in the above code, after the package is loaded, the following things happen:


πŸ’« logger::init service

initializes the service service for logging. here's the tea: service names are actually Tcl namespace names, so they're separated with '::'. the service name may not be the empty string, and it may not be only ':'s. noted. πŸ“

when a logger service is initialized, it "inherits" properties from its parents. for instance, if there were a service foo, and we did a logger::init foo::bar (to create a bar service underneath foo), bar would copy the current configuration of the foo service β€” although it would of course also be possible to then separately configure bar. yes, you can customize the baby logger after. πŸ’–

if a logger service is initialized and the parent does not yet exist, the parent is also created. the new logger service is initialized with the default loglevel set with logger::setlevel.


🧚 logger::import ?-all? ?-force? ?-prefix prefix? ?-namespace namespace? service

imports the logger service commands into the current namespace. okay so:

  • without the -all option, only the commands corresponding to the log levels are imported.
  • if -all is given, all the ${log}::cmd style commands are imported.
  • if the import would overwrite a command, an error is returned and no command is imported. use the -force option to force the import and overwrite existing commands without complaining.
  • if the -prefix option is given, the commands are imported with the given prefix prepended to their names.
  • if the -namespace option is given, the commands are imported into the given namespace. if the namespace does not exist, it is created. if a namespace without a leading :: is given, it is interpreted as a child namespace to the current namespace.

🌈 logger::initNamespace ns ?level?

a convenience command for setting up a namespace for logging. it:

  • creates a logger service named after the namespace ns (a :: prefix is stripped),
  • imports all the log commands into the namespace,
  • and sets the default logging level, either as specified by level, or inherited from a service in the parent namespace, or a hardwired default, warn.

⭐ logger::services

returns a list of all the available services. simple. clean. slay.


πŸ‘‘ logger::enable level

globally enables logging at and "above" the given level. the levels are debug, info, notice, warn, error, critical, alert, emergency.


πŸ™ˆ logger::disable level

globally disables logging at and "below" the given level. the levels are the same ones listed above. 🫢


πŸ’œ logger::setlevel level

globally enables logging at and "above" the given level. levels are those listed above. this command changes the default loglevel for new loggers created with logger::init.


πŸ“ logger::levels

returns a list of the available log levels (also listed above under enable). it's the same eight besties, no surprises.


πŸŽ€ logger::servicecmd service

returns the ${log} token created by logger::init for this service.


🌸 logger::debug, logger::info, logger::notice, logger::warn, logger::error, logger::critical, logger::alert, logger::emergency

${log}::debug message

${log}::info message

${log}::notice message

${log}::warn message

${log}::error message

${log}::critical message

${log}::alert message

${log}::emergency message

these are the commands called to actually log a message about an event. ${log} is the variable obtained from logger::init. that's the whole vibe. πŸ’…


πŸ’– ${log}::setlevel level

enables logging, in the service referenced by ${log}, and its children, at and above the level specified, and disables logging below it.


✨ ${log}::enable level

enables logging, in the service referenced by ${log}, and its children, at and above the level specified. ⚠️ note that this does not disable logging below this level, so you should probably use setlevel instead. fr fr.


πŸ¦‹ ${log}::disable level

disables logging, in the service referenced by ${log}, and its children, at and below the level specified. ⚠️ note that this does not enable logging above this level, so you should probably use setlevel instead.

disabling the loglevel emergency switches logging off for the service and its children. like, all the way off. be careful bestie.

🧚 ${log}::lvlchangeproc command / ${log}::lvlchangeproc

set the script to call when the log instance in question changes its log level. if called without a command it returns the currently registered command.

the command gets two arguments appended, the old and the new loglevel. the callback is invoked after all changes have been done. and if child loggers are affected, their callbacks are called before their parents callback. (children first, it's giving respect your elders but in reverse πŸ’€)

proc lvlcallback {old new} {
    puts "Loglevel changed from $old to $new"
}
${log}::lvlchangeproc lvlcallback

🌈 ${log}::logproc level / ${log}::logproc level command / ${log}::logproc level argname body

okay this one comes in three forms β€” and heads up, the third, older one is deprecated and may be removed from future versions of the logger package. πŸ‘€

the current set version takes one argument, a command to be executed when the level is called. the callback command takes on argument, the text to be logged. if called only with a valid level, logproc returns the name of the command currently registered as callback command.

logproc specifies which command will perform the actual logging for a given level. the logger package ships with default commands for all log levels, but with logproc it is possible to replace them with custom code. this would let you send your logs over the network, to a database, or anything else. the possibilities? endless. 🌈

for example:

proc logtoserver {txt} {
    variable socket
    puts $socket "Notice: $txt"
}

${log}::logproc notice logtoserver

trace logs are slightly different: instead of a plain text argument, the argument provided to the logproc is a dictionary consisting of the enter or leave keyword along with another dictionary of details about the trace. these include:

  • proc β€” Name of the procedure being traced.
  • level β€” The stack level for the procedure invocation (from info level).
  • script β€” The name of the file in which the procedure is defined, or an empty string if defined in interactive mode.
  • caller β€” The name of the procedure calling the procedure being traced, or an empty string if the procedure was called from the global scope (stack level 0).
  • procargs β€” A dictionary consisting of the names of arguments to the procedure paired with values given for those arguments (enter traces only).
  • status β€” The Tcl return code (e.g. ok, continue, etc.) (leave traces only).
  • result β€” The value returned by the procedure (leave traces only).

⭐ ${log}::services

returns a list of the registered logging services which are children of this service.


πŸ’œ ${log}::servicename

returns the name of this service. identity check, bestie. πŸ’…


πŸŽ€ ${log}::currentloglevel

returns the currently enabled log level for this service. if no logging is enabled it returns none.


πŸ“ ${log}::delproc command / ${log}::delproc

set the script to call when the log instance in question is deleted. if called without a command it returns the currently registered command. for example:

${log}::delproc [list closesock $logsock]

πŸ™ˆ ${log}::delete

this command deletes a particular logging service, and its children. you must call this to clean up the resources used by a service. don't leave it hanging, that's rude to your memory. 😭


πŸ¦‹ ${log}::trace command

this command controls logging of enter/leave traces for specified procedures. it is used to enable and disable tracing, query tracing status, and specify procedures are to be traced.

trace handlers are unregistered when tracing is disabled. as a result, there is not performance impact to a library when tracing is disabled, just as with other log level commands. ✨
proc tracecmd { dict } {
    puts $dict
}

set log [::logger::init example]
${log}::logproc trace tracecmd

proc foo { args } {
    puts "In foo"
    bar 1
    return "foo_result"
}
                proc bar { x } {
                    puts "In bar"
                    return "bar_result"
                }

                ${log}::trace add foo bar
                ${log}::trace on

                foo

              # Output:
              enter {proc ::foo level 1 script {} caller {} procargs {args {}}}
              In foo
              enter {proc ::bar level 2 script {} caller ::foo procargs {x 1}}
              In bar
              leave {proc ::bar level 2 script {} caller ::foo status ok result bar_result}
              leave {proc ::foo level 1 script {} caller {} status ok result foo_result}

so like, here's the tea on each trace subcommand:

  • ${log}::trace on β€” turns ON trace logging for all the procs you registered with trace add. It's giving similar energy to the enable command for other log levels, but it lets trace logging happen at ANY level. The whole thing is powered by Tcl 8.4+'s execution trace feature. Heads up: if you're on an older Tcl, trace on will straight up throw an error. πŸ’€
  • ${log}::trace off β€” turns OFF trace logging for the procs you registered with trace add. Similar to disable for other levels, but works at any level. The procs stay registered, so you can just trace on again to bring the logs back. And when it's off, there's literally zero overhead from having them registered. slay. ✨
  • ${log}::trace status ?procName? ?...? β€” spills the tea on which procs are currently registered for trace logging. If you pass one or more procNames, it'll just tell you whether a trace is registered for them or not. πŸ”
  • ${log}::trace add procName ?...? / ${log}::trace add ?-ns? nsName ?...? β€” registers one or more procs for entry/exit trace logging. You can give it a list of proc names or namespace names (and if it's a namespace, all procs inside that namespace get targeted). By default, each name is first treated as a proc name or glob-style pattern, and if that doesn't match, it's treated as a namespace name. The -ns option forces everything to be interpreted as namespace names. Important: procs MUST already be defined before you register them. And if any names/patterns don't match anything, they're just silently ignored. no drama. πŸ’…
  • ${log}::trace remove procName ?...? / ${log}::trace remove ?-ns? nsName ?...? β€” unregisters one or more procs so they stop getting trace logging. Same matching rules as trace add. bye bye πŸ‘‹

✨ IMPLEMENTATION ✨

so like, the logger package is built to be super optimized for Tcl 8.4+ when log procedures are disabled. They get aliased to a proc with no body, which compiles down to a no-op in bytecode. That means the performance hit is basically minimal. But if you're extra and want to squeeze out every drop of speed, you can replace the ${log} token in your code with the actual namespace and command (like ${log}::warn becomes ::logger::tree::myservice::warn), so no variable lookup happens. That makes disabled logger commands almost as fast as not logging at all. πŸ’…

The "object orientation" here is done through a hierarchy of namespaces. Using a real OO system would probably be better, or at least cleaner. But whatever.

The service "object orientation" is done with namespaces.


πŸ¦‹ LOGPROCS AND CALLSTACK πŸ¦‹

The logger package is super careful to keep the logproc OUT of the call stack. This means logprocs can run code in the caller's scope using uplevel, or link to local variables with upvar. This might fire traces with all the usual side effects. Here's an example:

                   # Print caller and current vars in the calling proc
                   proc log_local_var {txt} {
                        set caller [info level -1]
                        set vars [uplevel 1 info vars]
                        foreach var [lsort $vars] {
                           if {[uplevel 1 [list array exists $var]] == 1} {
                             lappend val $var <Array>
                           } else {
                             lappend val $var [uplevel 1 [list set $var]]
                           }
                        }
                        puts "$txt"
                        puts "Caller: $caller"
                        puts "Variables in callers scope:"
                        foreach {var value} $val {
                          puts "$var = $value"
                        }
                   }

                   # install as logproc
                   ${log}::logproc debug log_local_var

πŸ’€ BUGS, IDEAS, FEEDBACK πŸ’€

okay so this doc and the package? They're gonna have bugs, bestie. It's inevitable. Please report them in the logger category of the Tcllib Trackers at http://core.tcl.tk/tcllib/reportlist. Also, if you have ideas for enhancements for the package or the docs, slide them over there too. 🫢

If you're proposing code changes, send unified diffs, like the output of diff -u.

And one more thing: attachments are strongly preferred over inline patches. You can attach stuff by going to the Edit form of the ticket right after creating it, then hitting the left-most button in the secondary navigation bar.


🌈 KEYWORDS 🌈

log, log level, logger, service


πŸ‘‘ CATEGORY πŸ‘‘

Programming tools


This masterpiece comes from tcllib version 0.9.5, and it's the logger(3tcl) manual page. πŸ’–βœ¨

πŸ“¦ where this page comes from