【问题标题】:Printing message on the screen and also send to the syslog at the same time在屏幕上打印消息并同时发送到系统日志
【发布时间】:2013-09-02 10:46:35
【问题描述】:

我正在尝试在我的脚本中实现-s(即静默)选项 - 当给出错误/信息等时,将被发送到系统日志,否则会在屏幕上打印并发送到syslog同时。这就是我正在做的:

echo -e "This Is a Test Message\nWell, not really!!"  2>&1 | logger

将echo 消息发送到syslog(不会在屏幕上打印),但无法弄清楚如何同时进行这两项操作。我看到人们只谈论在屏幕上打印时使用syslog 记录或将日志发送到不同的文件,而不是我正在尝试处理的情况。任何帮助或指针将不胜感激。干杯!!

【问题讨论】:

  • 你可以通过管道发送到tee : ... | tee -a /var/log/syslog
  • 不要使用 tee -a /var/log/syslog - 只有 root 可以这样做,而 syslogd 可能会执行各种替代处理,而不仅仅是附加到该文件。
  • @hek2mgl:是的,但该文件因系统而异;例如/var/log/messages 用于基于 Red Hat 的系统。使用logger 更安全。干杯!!

标签: linux bash logging echo syslog


【解决方案1】:

如果您想将消息发送到 syslog 和 stdout(不是 stderr),您也可以这样做:

echo -e "This Is a Test Message\nWell, not really!!" | tee >(exec logger)

以及执行此操作的有效方法(如果您正在创建函数):

exec 40> >(exec logger)

function log {
    echo -e "$1"
    echo -e "$1" >&40
}

log "something..."

exec 40>&-  ## optionally close it at the end of the script.

这将使您的脚本免于在每次执行回显时调用外部二进制记录器。

【讨论】:

  • 函数怎么调用?
  • @konsolebox:我认为这是适合我的方式。所以,为了确定,如果我使用自定义文件描述符,除了使用echo 两次之外,没有别的办法吗?干杯!!
  • @Juto:您调用函数的方式就像 konsolebox 所做的那样:log "Print something..."。 log 是函数的名称。
  • 你也可以有 tee:exec 40> >(exec tee >(exec logger)),尽管我仍然建议只使用一个进程。无论如何,它仍然是一样的。输出在 tee 中重复。
  • 但是当然你使用另一个函数来发送输出到&40并且你只想做一次,那么新的方法可以应用。
【解决方案2】:

在这种情况下,只需将同一消息回显两次。你可以这样做:

echo -e "This Is a Test Message\nWell, not really!!" | tee /dev/stderr | logger

但是,实际上这样做更简单、更高效:

error='This Is a Test Message\nWell, not really!!'
echo -e "$error" >&2
echo -e "$error" | logger

>&2 将输出发送到 stderr,而不是 stdout。

【讨论】:

    【解决方案3】:

    你可以这样做:

    echo -e "This Is a Test Message\nWell, not really!!" | logger -s
    

    手册页(man logger)指出:

    -s     Log the message to standard error, as well as the system log.
    

    【讨论】:

    • 已经尝试过-s,但不喜欢它在消息前加上用户名:admin: This Is a Test..."。它也无法处理新行的\n,这对我不利。干杯!!
    • 我删除了 2>&1,因为它本质上是多余的 - 无论是否使用 -s 选项,它都不会在这里产生任何影响。
    猜你喜欢
    • 1970-01-01
    • 2019-11-02
    • 2018-10-14
    • 2021-03-12
    • 2015-09-08
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    • 2011-04-21
    相关资源
    最近更新 更多