Redirect stdout / stderr output to log file with timestamp

 To redirect both standard output (stdout) and standard error (stderr) to a log file with timestamps in a Unix-like system, you can use a command like this:


```bash

command > >(while IFS= read -r line; do echo "$(date '+%Y-%m-%d %H:%M:%S') $line"; done) 2> >(while IFS= read -r line; do echo "$(date '+%Y-%m-%d %H:%M:%S') $line" >&2; done) | tee -a logfile.log

```


Here's what this command does:


1. `command`: Replace this with the actual command whose output you want to capture.


2. `> >(while IFS= read -r line; do echo "$(date '+%Y-%m-%d %H:%M:%S') $line"; done)`: This redirects stdout to a process substitution, which prefixes each line with a timestamp in the format "YYYY-MM-DD HH:MM:SS".


3. `2> >(while IFS= read -r line; do echo "$(date '+%Y-%m-%d %H:%M:%S') $line" >&2; done)`: This redirects stderr to a process substitution, which also adds timestamps and sends the modified output to stderr.


4. `| tee -a logfile.log`: This pipes the combined output (stdout and stderr with timestamps) to the `tee` command, which appends it to a log file called "logfile.log" and also displays it in the terminal.


This way, you can capture both stdout and stderr, add timestamps, and save the output to a log file.

Comments

Popular posts from this blog

bad character U+002D '-' in my helm template

GitLab pipeline stopped working with invalid yaml error

How do I add a printer in OpenSUSE which is being shared by a CUPS print server?