Skip to content

Instantly share code, notes, and snippets.

@Spotlightsrule
Last active August 2, 2022 08:29
Show Gist options
  • Save Spotlightsrule/4ad6098bcc03c4ee9004da3def0522b0 to your computer and use it in GitHub Desktop.
Save Spotlightsrule/4ad6098bcc03c4ee9004da3def0522b0 to your computer and use it in GitHub Desktop.
Simple logger for bash scripts
#!/bin/bash
## SETUP (DO NOT EDIT) ##
logfile_name=${logfile_prefix}$(date +$logfile_date_format)"."${logfile_ext}
logfile_working_path=${logfile_location}"/"${logfile_name}
## -- ##
## FUNCTIONS ##
# log(contents) -> void
log(){
#Check if the logfile directory exists and create it if it doesn't
if [ ! -d "$logfile_location" ]; then
mkdir -p $logfile_location
#Announce to the console if allowed to
if [ $logger_debug -eq 1 ]; then echo "Logger directory ("${logfile_location}") is nonexistant. Creating it..."; fi
fi
#Check if the logfile exists
if [ ! -f "$logfile_working_path" ]; then
#Create the logfile via touch
touch $logfile_working_path
#Announce to the console if allowed to
if [ $logger_debug -eq 1 ]; then echo "Creating nonexistant logfile located at \""${logfile_working_path}"\"..."; fi
fi
#Generate the prefix if desired
local prefix=""
if [ $logger_include_time -eq 1 ]; then
prefix="["$(date +%T)"] "
fi
#Construct the final message
local message=${prefix}${@}
#Log the message to the file and the console (if desired)
echo ${message} >> ${logfile_working_path}
if [ $logger_quiet -eq 0 ]; then echo ${message}; fi
}
## -- ##
#!/bin/bash
## CONFIG FOR LOGGER ##
#Sets the location to store the logfiles. Relative to the current directory
logfile_location="logs/"
#Sets the logfile extension
logfile_ext="log"
#Sets the prefix for the logfiles
logfile_prefix="log_"
#Sets the date format for the logfiles, excluding the mandatory '+'. See https://www.tutorialkart.com/bash-shell-scripting/bash-date-format-options-examples/
logfile_date_format="%Y-%d-%m_%H-%M-%S"
#Sets whether to suppress console output (0: no, 1: yes)
logger_quiet=0
#Sets whether to allow console debug (0: no, 1: yes)
logger_debug=1
#Sets whether the time should be prefixed (ie: `[10:00:00] message`); (0: no, 1: yes)
logger_include_time=1
## -- ##
#Include log.sh
. ./log.sh --source-only
# Testing via fibonacci seq
n=$((0))
i=$((0))
j=$((1))
while [ $(($n < 90)) == 1 ]; do
k=$(($i + $j))
i="$j"
j="$k"
n=$(($n + 1))
log $k
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment