BASH: Separate logging

Developing bash script sometimes required to separate some kind of messages into another log file.

Also could be useful to save output data inside the pipe.

Under the cut you can see two functions to do that.

$ cat logging.inc log() { if [[ -t 0 ]]; then local RUN_LOG="${RUN_LOG:-/dev/null}" if [[ -t 1 ]]; then echo -e "$@" | debug | cat >> "$RUN_LOG" else echo -e "$@" | debug | tee -a "$RUN_LOG" fi else local RUN_LOG="${1:-${RUN_LOG:-/dev/null}}" if [[ -t 1 ]]; then cat | debug | cat >> "$RUN_LOG" else cat | debug | tee -a "$RUN_LOG" fi fi } debug() { if [[ -t 0 ]]; then local DEBUG_LOG="${DEBUG_LOG:-/dev/null}" if [[ -t 1 ]]; then echo -e "$@" | cat >> "$DEBUG_LOG" else echo -e "$@" | tee -a "$DEBUG_LOG" fi else local DEBUG_LOG="${1:-${DEBUG_LOG:-/dev/null}}" if [[ -t 1 ]]; then cat | cat >> "$DEBUG_LOG" else cat | tee -a "$DEBUG_LOG" fi fi }

The following example shows how this staff could be used:

$ cat /tmp/example.sh #!/bin/bash RUN_LOG="/tmp/runtime.run.log" DEBUG_LOG="/tmp/runtime.debug.log" . /tmp/logging.inc log "[LOG] argument example" debug "[DEBUG] argument example" echo "[LOG] pipe example" | log echo "[DEBUG] pipe example" | debug echo "[LOG] pipe continue example" | log | grep 'pipe' echo "[DEBUG] pipe continue example" | debug | grep 'pipe' $ bash /tmp/example.sh [LOG] pipe continue example [DEBUG] pipe continue example $ cat /tmp/runtime.run.log [LOG] argument example [LOG] pipe example [LOG] pipe continue example $ cat /tmp/runtime.debug.log [LOG] argument example [DEBUG] argument example [LOG] pipe example [DEBUG] pipe example [LOG] pipe continue example [DEBUG] pipe continue example

HH

Leave a Reply

Your email address will not be published. Required fields are marked *