2 # Copyright (C) 2016 Ian Kelling
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
8 # http://www.apache.org/licenses/LICENSE-2.0
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.
20 local help="Usage: log-once [OPTION]... LOG_NAME [LOG_MESSAGE]
22 For cronjobs, email only once for repeated failures, and for success after failure.
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).
29 Logs LOG_MESSAGE or STDIN to ~/.cron_errors/LOG_NAME, and keeps
30 state in the same directory.
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
36 if [[ $1 == --help ]]; then
39 elif [[ $1 == -[0-9]* ]]; then
42 elif [[ $1 == -- ]]; then
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
54 # http://stackoverflow.com/questions/2456750/detect-presence-of-stdin-contents-in-shell-script
58 # read stdin for anything which is not just a newline
59 elif [[ ! -t 0 ]]; then
67 if [[ -f $c$
((errors-1
)) ]]; then
72 for ((i
=errors
; i
>=1; i--
)); do
73 if [[ -f $c$
((i-1
)) ]]; then
79 if [[ ! $file ]]; then
80 if [[ -f $c$errors ]]; then
86 $out $file <<<"log-once: $(date "+%A, %B %d, %r")"
90 $out $file <<<"${output[@]}"
94 elif [[ -f $c$errors ]]; then
95 echo "log-once success after failure for $c"
98 rm -f $c[0-9]* # assuming no one is putting crazy files names, as this is not exact