diff options
| author | Jan Tuomi <jan@jantuomi.fi> | 2026-05-13 00:13:57 +0300 |
|---|---|---|
| committer | Jan Tuomi <jan@jantuomi.fi> | 2026-05-16 18:42:27 +0300 |
| commit | b5860daf11ac353049cb1654b9414a129e5cfb96 (patch) | |
| tree | 87ed89711e4f0e85ace0a97fa123199152c67302 /roles/host/templates/usr_local_bin_logto.sh.j2 | |
| parent | 4715a28fdcd87440400d17154bfa361d99db29cc (diff) | |
Rework
Diffstat (limited to 'roles/host/templates/usr_local_bin_logto.sh.j2')
| -rw-r--r-- | roles/host/templates/usr_local_bin_logto.sh.j2 | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/roles/host/templates/usr_local_bin_logto.sh.j2 b/roles/host/templates/usr_local_bin_logto.sh.j2 new file mode 100644 index 0000000..9bb5aa1 --- /dev/null +++ b/roles/host/templates/usr_local_bin_logto.sh.j2 @@ -0,0 +1,47 @@ +#!/bin/sh + +set -ue + +# Wrapper for logging to file and prepending a timestamp. +# By default writes both stdout and stderr to the log file. + +usage() { + echo "Usage: logto [-s|-e] <log_file> <command>" + echo "Flags:" + echo " -s: Write only stdout to the log file." + echo " -e: Write only stderr to the log file." + echo "" + echo "Example usage:" + echo " logto /var/log/my.log run some command" + exit 1 +} + +mode="all" + +while getopts "se" opt; do + case $opt in + s) mode="stdout" ;; + e) mode="stderr" ;; + *) usage ;; + esac +done +shift $((OPTIND-1)) + +if [ $# -lt 2 ]; then + usage +fi + +log_file="$1" +shift + +if [ "$mode" = "stdout" ]; then + out=$(2>/dev/null $@) +elif [ "$mode" = "stderr" ]; then + out=$(2>&1 >/dev/null $@) +else + out=$(2>&1 $@) +fi + +if [ ! -z "$out" ]; then + echo "$(date +"%Y-%m-%dT%H:%M:%S%z")" "$out" >>"$log_file" +fi |
