I’m developing a daemon written in Ruby and in the course of development
I
like to see various status messages printed at crucial points to aid in
debugging. Since this is a daemon, I use syslog and create a global
$log
variable to handle log messages, essentially like the following:
This has worked well as long as the whole program is contained in a
single
file, but as the program has gradually increased in complexity, I wish
to
remove the definition of some classes to their own files and “require”
them
in the main ruby source file. This means that whatever is removed to a
separate file no longer has access to the global variable $log. Any
suggestions on how to best handle status/debug messages from these
subsidiary files?
I wish
to
remove the definition of some classes to their own files and “require”
them
in the main ruby source file. This means that whatever is removed to a
separate file no longer has access to the global variable $log.
Why? A global variable is global - it should be visible from any file.
As long as your main program initialises $log before any of the
subsidiary files try to use it, you should be fine.
Are you saying you want to run these subsidiary files by themselves,
independent from the main program which initialises $log?
One way to do that is to initialise $log in a separate library.
Note that the Syslog API is Syslog.debug, Syslog.warning etc. So you
don’t actually need to set up a global variable, but if you do, it
should be set to Syslog (which is also the value returned by
Syslog.open)
An advantage of setting $log is that you can point it to a different
object with a duck-type interface. Logger has a similar interface,
although annoyingly it’s Logger#warn vs Syslog.warning