I usually use Bash for fairly trivial and/or ad-hoc tasks. But
sometimes when a Bash program become complex, leveled logging can
be useful for debugging and monitoring program states. By leveled
logging, I mean printing messages grouped by different tags such as
DEBUG
and INFO
and controlling which of
the groups are printed by a "level" parameter. This is roughly
what's supported by
java.util.logging.Level
and
org.apache.log4j.Level
in Java.
To do this in Bash, I simply defined a set of level constants that is the union of the two schemes given above:
LEVEL |
java.util.logging.Level |
org.apache.log4j.Level |
---|---|---|
9 | (off) | (off) |
8 | n/a | FATAL |
7 | SEVERE |
ERROR |
6 | WARNING |
WARN |
5 | INFO |
INFO |
4 | CONFIG |
n/a |
3 | FINE |
DEBUG |
2 | FINER |
TRACE |
1 | FINEST |
ALL |
and define a mengLog
function that print a message
if the message's logging level is same or higher than a global
logging level $mengLOGGING_LEVEL
. So the logging level
can be understood as an indication of priority, the higher the
level is, the higher the priority. For instance, when
$mengLOGGING_LEVEL=6
, messages with level equal or
higher than 6
has an enough priority or even higher
priority to be printed, and therefore, WARNING/WARN, SEVERE/ERROR,
FATAL messages are printed in the example
leveled-logging_example.sh
.
Code: