Thursday, July 7, 2016

Logger Module: INFO and ERROR for your BASH scripts

G=$(tput setaf 2) # Green for info
R=$(tput setaf 1) # Red for error
M=$(tput setaf 5) # Magenta for others
N=$(tput sgr0) # Reset the color
LOGDIR="/var/log"
LOG_FILE=mylog.log
log_dir_check()
{
if [ -d $LOGDIR ]
then
    echo "Directory already existing"
else
    mkdir -p $LOGDIR
fi
}
log_info()
{
    local msg="$1"
    local tstamp=`date '+%b%e %H:%M:%S'`
    echo -e "$G$tstamp:[INFO] $msg$N" 2>&1 | tee -a $LOGDIR/$LOG_FILE
}
log_error()
{
    local msg="$1"
    local tstamp=`date '+%b%e %H:%M:%S'`
    echo -e "$R$tstamp:[ERROR] $msg$N" 2>&1 | tee -a $LOGDIR/$LOG_FILE
}
log_dir_check
log_error "This is an error"
log_info "This is an info"


onscreen and log o/p

# cat /var/log/mylog.log
Jul 8 02:48:49:[ERROR] This is an error
Jul 8 02:48:49:[INFO] This is an info


No comments:

Post a Comment