bash 如何使用 logger 命令登录到 linux 中的特定文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13423303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 22:58:34  来源:igfitidea点击:

How can I log to a specific file in linux using logger command?

bashlogging

提问by alwbtc

I will run the following script:

我将运行以下脚本:

#!/bin/bash
./myprogram

#get exit code
exitvalue=$?

#log exit code value to /var/log/messages
logger -s "exit code of my program is " $exitvalue

But I don't want log message to be written in /var/log/messagesbecause I don't have root privileges. Instead I want it to be written to a file in my home directory: /home/myuser/mylog

但我不希望写入日志消息,/var/log/messages因为我没有 root 权限。相反,我希望将其写入主目录中的文件:/home/myuser/mylog

How should I modify loggercommand above?

我应该如何修改logger上面的命令?

回答by twalberg

I don't think you really need to (or want to) involve logger/syslogfor this. Simply replace the last line of the script with:

我不认为你真的需要(或想要)参与logger/syslog为此。只需将脚本的最后一行替换为:

echo "Exit code of my program is $exitvalue" >> /some/file/that/you/can/write/to

回答by Basile Starynkevitch

If you want to use loggerso that the message appears both in the system logs and in some file of yours, you might do

如果您想使用logger该消息同时出现在系统日志和您的某些文件中,您可以这样做

  logger -s your message 2> $HOME/somefile

since the -soption to loggeralso outputs on stderrwhich is redirected to the file with 2>

因为还可以在stderr输出-s选项被重定向到文件logger2>

You could want to use 2>> $HOME/somefileto append (not overwrite) your $HOME/somefile(read about bashredirections), and (see logger(1)for details) you may prefer to pass the program option --id=$$to logger.

您可能希望使用2>> $HOME/somefile附加(而不是覆盖)您的$HOME/somefile(阅读bash重定向),并且(有关详细信息,请参阅logger(1))您可能更愿意将程序选项传递--id=$$logger.

回答by Sz.

The short "official" answer is that, unfortunately, you can't.

简短的“官方”答案是,不幸的是,你不能。

However, in most cases (e.g. on many Linux distros) you may just be lucky enough to have a loggerimplementation that both supports the --no-actoption, and also implements some message formatting on its own (see below), in which case you can use a (moderately ugly) command like this to put a) a properly formatted message, b) to a file, c) not polluting the system logs:

但是,在大多数情况下(例如在许多 Linux 发行版上),您可能只是幸运地拥有一个logger既支持该--no-act选项又自己实现一些消息格式的实现(见下文),在这种情况下,您可以使用 (适度丑陋)这样的命令可以将 a) 格式正确的消息,b) 放入文件,c) 不污染系统日志:

logger --no-act -s "Oh dear..." 2>&1 | sed 's/^<[0-9]\+>//' >> /tmp/my.log

(Shout out to @BasileStarynkevitch, and @Kieveli, who both mentioned parts of it before, just not the whole story.)

(向@BasileStarynkevitch 和@Kieveli 大喊大叫,他们之前都提到过部分内容,只是不是整个故事。)

Notes:

笔记:

1) To match the usual log file format, I had to "sed off" the <PRIVAL>field (PRIVAL= FACILITY* 8 + PRIORITY) that got prepended to the output on my Debian boxes. Your mileage may vary.

1) 为了匹配通常的日志文件格式,我不得不“关闭”我的 Debian 机器上的输出前面的<PRIVAL>字段 ( PRIVAL= FACILITY* 8 + PRIORITY)。你的旅费可能会改变。

2) POSIX itself does notdefine how exactly the loggercommand should treat (any of) its options. E.g. the GNU loggerdoes not support --no-actat all. Also, when posting the original version of this answer 2 years ago, -son my system did notdo any formatting to the printed output, it just echoed the raw message alone, rendering it completely useless. (I didn't use Systemd at that time, which might explain the difference, seeing various conditional Systemd-related calls in the logger source code, but this is just vague guesswork.)

2) POSIX 本身并没有定义logger命令应该如何处理它的(任何)选项。例如,GNU 记录器根本不支持--no-act。另外,2年前发布这个答案的原始版本的时候,-s我的系统上并没有做任何格式的打印输出,它只是呼应了原始消息孤单,使其完全无用。(我当时没有使用 Systemd,这可能可以解释差异,在记录器源代码中看到各种与 Systemd 相关的条件调用,但这只是模糊的猜测。)

3) The most likely reason why the loggercommand has been so "historically unfriendly" for this trivial use case is that it's just a fairly simple frontend to the system logger. This means that anything you feed to it basically goes right through to syslogd(or systemd-journaldetc.), which, in turn, does all sorts of other further processing, and dispatching (to various outlets: files, sockets etc., both local and remote), as well as bridging permission levels (so in your example you could still log to syslogor user.log, for instance, even though you may have no permission to write to those files directly).

3)logger对于这个微不足道的用例,该命令在“历史上不友好”的最可能原因是它只是系统记录器的一个相当简单的前端。这意味着您提供给它的任何内容基本上都会直接通过syslogd(或systemd-journald等),然后进行各种其他进一步处理和分派(到各种出口:文件、套接字等,本地和远程) ,以及桥接权限级别(因此在您的示例中,您仍然可以登录sysloguser.log,例如,即使您可能没有直接写入这些文件的权限)。

For loggerto be able to properly log to a file directly, it would either have to (re)implement some of the duties of the system logger, and the syslog()std. library function, or it would be not much more capable than a trivial echo one-liner (less complex, perhaps, even than the above loggerinvocation! ;) ). Either way, that seems like a bad idea.

为了logger能够直接正确地登录到文件,它要么必须(重新)实现系统记录器的一些职责,要么必须执行syslog()标准。库函数,或者它不会比一个简单的 echo one-liner 更强大(可能比上面的logger调用更简单!;))。无论哪种方式,这似乎都是一个坏主意。

A better solution could be if the POSIX interface (logger, syslog()) had a way to specify an ad-hoc outlet/facility parameter (like a filename) along with the message, so one could log to custom files without reconfiguring the system (which normal users have no permission to do anyway).

一个更好的解决方案可能是,如果 POSIX 接口(loggersyslog())有一种方法可以指定一个 ad-hoc 插座/设施参数(如文件名)以及消息,这样就可以在不重新配置系统的情况下登录到自定义文件(普通用户无论如何都无权这样做)。

However, for the lack of anything better, the "canonical" Linux loggerimplementationactually does seem to duplicate some of the syslog functionality, so most of us can just enjoy that luxury for free. ;)

然而,由于缺乏更好的东西,“规范的”Linuxlogger实现实际上似乎复制了一些系统日志功能,所以我们大多数人可以免费享受这种奢侈。;)

回答by tgharold

I think your better choice would be to use the datecommand rather then loggerin cases where you don't want to write to the syslog files (and don't have privs to do so).

我认为您更好的选择是使用该date命令,而不是logger在您不想写入 syslog 文件的情况下(并且没有这样做的权限)。

See "timestamp before an echo" for details on how to use dateto prefix a message with a date and write it to a file.

有关如何使用日期作为消息前缀并将其写入文件的详细信息,请参阅“回声之前的时间戳date

You create a bash function that looks like the following, adjusting the dateformat string to get what you want:

您创建一个如下所示的 bash 函数,调整date格式字符串以获得所需的内容:

echo_time() {
    echo `date +'%b %e %R '` "$@"
}

In your bash script, you would then use:

在您的 bash 脚本中,您将使用:

echo_time "Your message here" >> ${LOGFILE}

Which would put the following in your ${LOGFILE}file:

这会将以下内容放入您的${LOGFILE}文件中:

Mar 11 08:40 your message here

回答by Jeff Ferland

$ man logger

Logger provides a shell command interface to the syslog(3) system log module.

Logger 为 syslog(3) 系统日志模块提供了一个 shell 命令接口。

You'll need to change your syslog configuration if you want it to log things to other places. You could establish a certain facilitythat has an output file in your home directory, for example. You would need to be root to do that, though.

如果您希望将内容记录到其他位置,则需要更改 syslog 配置。例如,您可以建立一个在您的主目录中具有输出文件的特定设施。不过,您需要成为 root 用户才能做到这一点。

回答by ravi katiyar

You can create a small logger function like this on top of your script file:

您可以在脚本文件之上创建一个像这样的小型记录器函数:

#! /bin/bash

#LOG FILE location
log_file=/tmp/mylogfile.log

#the LOG function
LOG()
{
time=$(date '+%Y-%m-%d %H:%M:%S')
echo "$time"" >>> " >>${log_file}
}


message= echo "test logger message"
#to send loggers to your log file use
LOG "my message logged to my log file with timestamp = ""$message" 

check output :

检查输出:

head -1 /tmp/mylogfile.log
2019-09-16 14:17:46 >>> my message logged to my log file with timestamp = test logger message

回答by lucas

I you can use cat -witch echoes your output then >> [file]witch prints the output to [file]inset of terminal so the command would be

我可以使用cat -女巫回显您的输出然后>> [file]女巫将输出打印到[file]终端的插图中,因此命令将是

cat - >> [file]

the down side is you have to use ctrl+C or ctrl+Z to exit loggeris better for online code

不利的一面是您必须使用 ctrl+C 或 ctrl+Z 退出logger对在线代码更好