Writing outputs to log file and console

2019-03-07 14:28发布

In Unix shell, I have a env file (env file defines the parameters required for running the user script like log file name and path, redirect outputs and errors to log file, database connection details, etc) which redirects all the outputs (echo messages) and errors to the log file from the executed script using the following code:

exec 1>>${LOG_FILE}
exec 2>>${LOG_FILE}

The env file is executed at the beginning of each script. Due to the above code in env file all the console outputs that might be user outputs or errors are directly output to the log file which is what I actually needed.

But there are some selective user outputs which I want to be displayed in both the console and the log file. But because of the above code I am not able to do so.

I know that if I remove the above code I can get the desired result for this case, but I will have to manually write all other outputs to the log file which is not an easy task.

Is there a way to get the output in both the console and the log file without removing the above codes?

9条回答
何必那么认真
2楼-- · 2019-03-07 14:51

I find it very useful to append both stdout and stderr to a log file. I was glad to see a solution by alfonx with exec > >(tee -a), because I was wondering how to accomplish this using exec. I came across a creative solution using here-doc syntax and .: https://unix.stackexchange.com/questions/80707/how-to-output-text-to-both-screen-and-file-inside-a-shell-script

I discovered that in zsh, the here-doc solution can be modified using the "multios" construct to copy output to both stdout/stderr and the log file:

#!/bin/zsh
LOG=$0.log
# 8 is an arbitrary number;
# multiple redirects for the same file descriptor 
# triggers "multios"
. 8<<\EOF /dev/fd/8 2>&2 >&1 2>>$LOG >>$LOG
# some commands
date >&2
set -x
echo hi
echo bye
EOF
echo not logged

It is not as readable as the exec solution but it has the advantage of allowing you to log just part of the script. Of course, if you omit the EOF then the whole script is executed with logging. I'm not sure how zsh implements multios, but it may have less overhead than tee. Unfortunately it seems that one cannot use multios with exec.

查看更多
小情绪 Triste *
3楼-- · 2019-03-07 14:56

Try this, it will do the work:

log_file=$curr_dir/log_file.txt
exec > >(tee -a ${log_file} )
exec 2> >(tee -a ${log_file} >&2)
查看更多
Bombasti
4楼-- · 2019-03-07 14:57

for log file you may date to enter into text data. following code may help

# declaring variables

Logfile="logfile.txt"   
MAIL_LOG="Message to print in log file"  
Location="were is u want to store log file"

cd $Location   
if [ -f $Logfile ]  
then   
echo "$MAIL_LOG " >> $Logfile

else        

touch $Logfile   
echo "$MAIL_LOG" >> $Logfile    

fi  

ouput: 2. Log file will be created in first run and keep on updating from next runs. In case log file missing in future run , script will create new log file.

查看更多
登录 后发表回答