make log-once be script instead of function
[log-quiet] / log-once
1 #!/bin/bash
2 # Copyright (C) 2016 Ian Kelling
3
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7
8 # http://www.apache.org/licenses/LICENSE-2.0
9
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 append() {
17 cat >> "$1"
18 }
19 log-once() {
20 local help="Usage: log-once [OPTION]... LOG_NAME [LOG_MESSAGE]
21
22 For cronjobs, email only once for repeated failures, and for success after failure.
23
24 Meant for use in cronjobs where LOG_MESSAGE or STDIN represents an error,
25 but we only want to output that to STDOUT if we've seen this type of
26 error ERRORS(default 3) number of times in a row, then we don't
27 want to output anything again until we've seen a success (an empty LOG_MESSAGE).
28
29 Logs LOG_MESSAGE or STDIN to ~/.cron_errors/LOG_NAME, and keeps
30 state in the same directory.
31
32 -e ERRORS: ERRORS is the number of errors to accumulate before outputing the error"
33 local cbase c c1 c2 log x i out file
34 errors=3
35 while true; do
36 if [[ $1 == --help ]]; then
37 echo "$help"
38 return
39 elif [[ $1 == -[0-9]* ]]; then
40 errors={$1#-}
41 shift
42 elif [[ $1 == -- ]]; then
43 shift
44 break
45 else
46 break
47 fi
48 done
49 log_name=$1
50 # todo, make option & make them overridable based on command line or env variable
51 cbase=$HOME/.cron-errors
52 [[ -d $cbase ]] || mkdir -p $cbase
53 c=$cbase/$log_name
54 # http://stackoverflow.com/questions/2456750/detect-presence-of-stdin-contents-in-shell-script
55 log=false
56 if [[ $2 ]]; then
57 log=true
58 # read stdin for anything which is not just a newline
59 elif [[ ! -t 0 ]]; then
60 while read -r x; do
61 output+=( $x )
62 [[ $x ]] && log=true
63 done
64 fi
65 if $log; then
66 file=
67 if [[ -f $c$((errors-1)) ]]; then
68 out="tee -a"
69 else
70 out=append
71 fi
72 for ((i=errors; i>=1; i--)); do
73 if [[ -f $c$((i-1)) ]]; then
74 file=$c$i
75 mv $c$((i-1)) $file
76 break
77 fi
78 done
79 if [[ ! $file ]]; then
80 if [[ -f $c$errors ]]; then
81 file=$c$errors
82 else
83 file=${c}1
84 fi
85 fi
86 $out $file <<<"log-once: $(date "+%A, %B %d, %r")"
87 if [[ $2 ]]; then
88 $out $file <<<"$2"
89 else
90 $out $file <<<"${output[@]}"
91 $out $file
92 fi
93 return 1
94 elif [[ -f $c$errors ]]; then
95 echo "log-once success after failure for $c"
96 rm -f $c$errors
97 else
98 rm -f $c[0-9]* # assuming no one is putting crazy files names, as this is not exact
99 fi
100 return 0
101 }
102 log-once "$@"