logging.sh 2.47 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
#
# LECA Bash library
#
# The LECA bash library provides a set of function used for helping
# development of bash script mainly to write job script on the luke
# cluster
#
# The files from the LECA Bash library must be sourced from your main script
#
#
# Logging facilities for bash
# ===========================
#
# Provides the following functions:
#
#  openlogfile <FILENAME>
#    Redirected all logging to the file specified by FILENAME.
#    If the file already exists, new logs are appened at the end of the file.
#    If the file does not exist it is created
#
#  closelogfile
#    Closes the current logfile and redirect the logging to stderr.
#
#  logdebug <MESSAGE>
#    Writes message as a debug level log to the current log file.
#
#  loginfo <MESSAGE>
#    Writes message as an info level log to the current log file.
#
#  logwarning <MESSAGE>
#    Writes message as a warning level log to the current log file.
#
#  logerror <MESSAGE>
#    Writes message as an error level log to the current log file.
#
#  setloglevel <LEVEL>
#    Set the current logging level to the level specified by LEVEL.
#    Level is DEBUG, INFO, WARNING or ERROR.
#    A log is recorded only when it is submitted with a level
#    greater or equal to the current logging level.
#
# All the log will be done on file descriptor 3
# By default file descriptor 3 is redirected to stderr (2)
# By default the logging level is set to WARNING.
# Therefore only WARNING and ERROR messages will be actually logged.

LOG_DEBUG_LEVEL=1
LOG_INFO_LEVEL=2
LOG_WARNING_LEVEL=3
LOG_ERROR_LEVEL=4

LOG_LEVEL=2

exec 3>&2

#####
#
# The logging function

function logdebug() {
	if (( LOG_LEVEL <= LOG_DEBUG_LEVEL )); then
Eric Coissac committed
62
		echo `date +'%Y-%m-%d %H:%M:%S'` "[DEBUG  ] $(hostname).$$ -- $*" 1>&3
63 64 65 66 67
	fi
}

function loginfo() {
	if (( LOG_LEVEL <= LOG_INFO_LEVEL )); then
Eric Coissac committed
68
		echo `date +'%Y-%m-%d %H:%M:%S'` "[INFO   ] $(hostname).$$ -- $*" 1>&3
69 70 71 72 73
	fi
}

function logerror() {
	if (( LOG_LEVEL <= LOG_ERROR_LEVEL )); then
Eric Coissac committed
74
		echo `date +'%Y-%m-%d %H:%M:%S'` "[ERROR  ] $(hostname).$$ -- $*" 1>&3
75 76 77 78 79
	fi
}

function logwarning() {
	if (( LOG_LEVEL <= LOG_WARNING_LEVEL )); then
Eric Coissac committed
80
		echo `date +'%Y-%m-%d %H:%M:%S'` "[WARNING] $(hostname).$$ -- $*" 1>&3
81 82 83 84 85
	fi
}

function setloglevel () {
	LOG_LEVEL=$(indirect "LOG_${1}_LEVEL")
86
	loginfo "Logging level set to : ${1} ($LOG_LEVEL)"
87 88 89 90 91 92 93 94 95 96 97 98 99 100
}

function openlogfile() {
	exec 3>> "$1"
	LOGFILE="$1"
}

function closelogfile() {
	if [[ ! -z "${LOGFILE}" ]]; then
		exec 3>&-
		exec 3>&2
		LOGFILE=""
	fi
}
101 102

logdebug "Load logging package"