Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
1
0
 
0
Language: Bash
Posted by: Gerrit Viljoen
Added: Oct 10, 2014 9:58 AM
Modified: Oct 11, 2014 10:12 AM
Views: 81
Write input to log file, with a timestamp. Rolls log file when it's bigger than 2MB.

echo 'Log this please' | rollog /var/log/test.log
  1. #!/bin/bash
  2.  
  3. #Failfast block
  4. error_handler() {
  5.     echo "Error at line ${1} returned ${2}"
  6. }
  7. trap 'error_handler ${lineNO} $?' ERR
  8. set -o nounset
  9. set -o errexit
  10. set -o pipefail
  11.  
  12. #Check arguments
  13. if [[ -z "$@" ]]
  14. then
  15.     echo 'usage: [output] | rollog [file]'
  16.     exit 1
  17. else
  18.     log_file="$@"
  19.     log_dir=$(dirname "$log_file")
  20.     second_log_file="$log_file.1"
  21. fi
  22.  
  23. #Make sure that the log file exists
  24. if [[ ! -d "$log_dir" ]]
  25. then
  26.     mkdir -p "$log_dir"
  27. fi
  28. touch "$log_file"
  29.  
  30. #Roll log file
  31. log_size=$(stat -c '%s' "$log_file")
  32. log_size_threshold=$((2 * 1024 * 1024)) #2MB
  33. if [[ "$log_size" -gt "$log_size_threshold" ]]
  34. then
  35.     rm -f "$second_log_file"
  36.     mv "$log_file" "$second_log_file"
  37.     touch "$log_file"
  38. fi
  39.  
  40. #Read from std input (line by line) and write to log file
  41. while read line
  42. do
  43.     echo "$(date +'%F %T') - $line" >> "$log_file"
  44. done
  45.