将输出写入日志文件和控制台 [英] Writing outputs to log file and console

查看:751
本文介绍了将输出写入日志文件和控制台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Unix shell中,我有一个env文件( env文件定义了运行用户脚本所需的参数,例如日志文件名和路径,将输出和错误重定向到日志文件,数据库连接详细信息等),它使用以下代码将从执行脚本中的所有输出( echo消息)和错误重定向到日志文件:

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}

env文件在每个脚本的开头执行.由于上述env文件中的代码,所有可能是用户输出或错误的控制台输出都将直接输出到日志文件,这正是我真正需要的.

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?

推荐答案

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

会将stdout和stderr输出发送到日志文件中,但也会使fd 3连接到控制台,因此您可以这样做

would send stdout and stderr output into the log file, but would also leave you with fd 3 connected to the console, so you can do

echo "Some console message" 1>&3

仅将消息写到控制台,或者

to write a message just to the console, or

echo "Some console and log file message" | tee /dev/fd/3

向控制台和日志文件都写入消息-tee将其输出发送到自己的fd 1(这里是LOG_FILE )和您要写入的文件(这里是fd 3,即控制台).

to write a message to both the console and the log file - tee sends its output to both its own fd 1 (which here is the LOG_FILE) and the file you told it to write to (which here is fd 3, i.e. the console).

示例:

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

echo "This is stdout"
echo "This is stderr" 1>&2
echo "This is the console (fd 3)" 1>&3
echo "This is both the log and the console" | tee /dev/fd/3

将打印

This is the console (fd 3)
This is both the log and the console

在控制台上放置

This is stdout
This is stderr
This is both the log and the console

进入日志文件.

这篇关于将输出写入日志文件和控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆