Improving @Fred's idea is a bit more, we could create a small registration library this way:
declare -A _log_levels=([FATAL]=0 [ERROR]=1 [WARN]=2 [INFO]=3 [DEBUG]=4 [VERBOSE]=5) declare -i _log_level=3 set_log_level() { level="${1:-INFO}" _log_level="${_log_levels[$level]}" } log_execute() { level=${1:-INFO} if (( $1 >= ${_log_levels[$level]} )); then "${@:2}" >/dev/null else "${@:2}" fi } log_fatal() { (( _log_level >= ${_log_levels[FATAL]} )) && echo "$(date) FATAL $*"; } log_error() { (( _log_level >= ${_log_levels[ERROR]} )) && echo "$(date) ERROR $*"; } log_info() { (( _log_level >= ${_log_levels[INFO]} )) && echo "$(date) INFO $*"; } log_debug() { (( _log_level >= ${_log_levels[DEBUG]} )) && echo "$(date) DEBUG $*"; } log_verbose() { (( _log_level >= ${_log_levels[VERBOSE]} )) && echo "$(date) VERBOSE $*"; }
Let's say that the above source is in a library file called logging_lib.sh, we could use it in a regular shell script as follows:
#!/bin/bash source /path/to/lib/logging_lib.sh set_log_level DEBUG log_info "Starting the script..."
Result:
Fri Feb 24 06:48:18 UTC 2017 INFO Starting the script... Fri Feb 24 06:48:18 UTC 2017 === command output start === Fri Feb 24 06:48:18 UTC 2017 === command output end === Fri Feb 24 06:48:18 UTC 2017 DEBUG This is a debug statement Fri Feb 24 06:48:18 UTC 2017 ERROR This is an error Fri Feb 24 06:48:18 UTC 2017 FATAL This is a fatal error
As we can see, log_verbose did not produce any output, since the log level is on DEBUG, one level below VERBOSE. However, log_debug_file date.out did indeed output the result, as well as log_execute INFO , as the log level is set to DEBUG, which is = INFO.
Using this as a base, we could also write shells if we need even finer tuning:
git_wrapper() {
With their help, the script could be strengthened to accept the argument --log-level level , which can determine the verbosity of the log with which it should work.
If anyone is interested to know why some variables are named with leading underscores in the code above, see this post:
source share