Last active
July 31, 2022 01:19
-
-
Save thommyhh/cb379f788ac9b5805a32085aa8e86cda to your computer and use it in GitHub Desktop.
Nice logging for bash scripts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# Takes stdin as message and prepends timestamp and severity and writes it into the given log file | |
function log() { | |
file=$1 | |
severity=$2 | |
while read text | |
do | |
LOGTIME=$(date "+%Y-%m-%d %H:%M:%S") | |
touch $file | |
if [ ! -f $file ]; then | |
echo "ERROR! Cannot log to $file." | |
exit 1 | |
fi | |
echo "$LOGTIME :: $severity :: $text" >> $file | |
done | |
} | |
# Echos the message into stderr | |
function error() { | |
message=$1 | |
echo $message >&2 | |
} | |
################# | |
# Usage: | |
# | |
# # Include logging function | |
# . $(realpath "$(dirname $0)/includes/log.sh") | |
# | |
# # Define log file | |
# LOGFILE=/var/log/backup.log | |
# | |
# # Set up redirection: | |
# Pipe stdout into log function with $LOGFILE and "INFO" severity | |
# exec 1> >(log $LOGFILE "INFO") | |
# Pipe stderr into log function with $LOGFILE and "ERROR" severity | |
# exec 2> >(log $LOGFILE "ERROR") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment