This is a very common scenario to log the application messages into a separate file; Here, we will see a Shell script how to write logs in a separate file.
Shell Script How to write logs in a separate file:
To make this use-case simple and more reusable, I am writing two different script files one is to write the messages to the log file, and another one is for generating the logs.
Create log_functions.sh file which will be responsible for logging the different types of log messages like INFO
, WARN
and ERROR
into application.log file.
/home/log_functions.sh
#!/bin/bash
VAR_LOG_DIR="/home/"
VAR_LOG_FILE="application.log"
logWarn(){
echo "--[`date "+%Y/%m/%d %H:%M:%S"`] -- WARN -- $@" >> ${VAR_LOG_DIR}/${VAR_LOG_FILE};
}
logInfo(){
echo "--[`date "+%Y/%m/%d %H:%M:%S"`] -- INFO -- $@" >> ${VAR_LOG_DIR}/${VAR_LOG_FILE};
}
logError(){
echo "--[`date "+%Y/%m/%d %H:%M:%S"`] -- ERROR -- $@" >> ${VAR_LOG_DIR}/${VAR_LOG_FILE};
exit 1;
}
Create a simple shell script to write some messages into application.log
file.
/home/log_messages.sh
#!/bin/bash
#Getting current directory
readonly CURRENT_DIR=$(cd `dirname $0`; pwd -P)
source ${CURRENT_DIR}/log_functions.sh
logInfo "I am information"
logWarn " I am a Warning message"
logError "I am an Error"
Make both files as executable.
$chmod 777 log_functions.sh
$chmod 777 log_messages.sh
Run log_messages.sh file and see the application.log file.
$./log_messages.sh
check the application.log file
$ more application.log
--[2020/04/16 15:41:07] -- INFO -- I am information
--[2020/04/16 15:41:07] -- WARN -- I am a Warning message
--[2020/04/16 15:41:07] -- ERROR -- I am an Error
Happy Learning 🙂