-
Notifications
You must be signed in to change notification settings - Fork 1
/
bash_logging.config
executable file
·49 lines (41 loc) · 1.83 KB
/
bash_logging.config
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
#!/bin/bash
#This is a list of functions used for creating and updating logs for bash scripts.
#This function creates a log at a specific directory
function logCreate {
configLogPath="${1}"
timestamp=$(date "+%Y-%m-%d - %H.%M.%S")
touch "${configLogPath}"
echo "====== Script started at $timestamp ======" >> "${configLogPath}"
}
#This function opens the log
function logOpen {
open "${configLogPath}"
}
function logNewLine {
timestamp=$(date "+%Y-%m-%d - %H.%M.%S")
echo -e "$timestamp - ${1}" >> "${configLogPath}"
}
function logCurrentLine {
sed -i '' -e '$s/$/'"$1"'/' "${configLogPath}" #this was a doozy to write. the -i '' -e is required for MacOS for some reason
}
##This function logs the beginning and end of a command, and calculates the total time
#got the prtinf statement from here: https://stackoverflow.com/questions/46471979/logging-inside-a-bash-script-file
#got the seconds thing from https://unix.stackexchange.com/questions/271406/how-to-log-command-start-time-and-command-end-time-in-txt-file-using-cygwin
function logLog {
SECONDS=0 &&
echo -e "$(date "+%Y-%m-%d - %H.%M.%S") ******** Command Started \n $(printf ' %q' "$@")" >> "${configLogPath}" &&
#print timestamp and command to log
"$@" &&
#runs the command
echo "$(date "+%Y-%m-%d - %H.%M.%S") ******** Comand Completed" >> "${configLogPath}" &&
#prints timestamp once the command has exited
duration=$SECONDS
echo " Total Execution Time: $(($duration / 60)) m $(($duration % 60)) s" >> "${configLogPath}"
}
#When this function is placed in a script, the stdout and the stderr will be saved to the log (but not printed to console)
function logOut {
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>>"${configLogPath}" 2>&1
#this is lifted directly from https://serverfault.com/questions/103501/how-can-i-fully-log-all-bash-scripts-actions
}