在 Bash 脚本中使用日志记录

Sib*_* JV 5 bash logging

我有一个 bash 脚本,我需要从中写入日志。目前我使用像下面这样的块

#log stop request
            {
                local now=$(date +"%a %b %d %Y %H:%M:%S")

                printf "batch stop request successful. \n"
                printf "      Time            :: %s\n" "$now"
                printf "      PID of process  :: %s\n" ${PID[0]}"
            } >> "${mylogfile}"
Run Code Online (Sandbox Code Playgroud)

其中 mylogfile 变量将包含日志文件的名称。

这种方法的问题在于,当 2 个或更多实例运行时,日志往往会因实例的交错写入而变得混乱。

请注意,我使用该块认为这会导致日志一次性写入文件,从而避免了该问题。

我在Vivek Gite 帖子中看到了 logger 命令。但问题是它不会写入我可以指定的文件,而是写入 /var/log/message。

任何帮助深表感谢。

谢谢并问候西比

she*_*ter 1

尝试将 3 个 printfs 作为一个字符串,即

printf "Epsilon batch stop request successful. \n      Time            :: %s\n     PID of process  :: %s\n" "$now"  ${PID[0]}
Run Code Online (Sandbox Code Playgroud)

您可能仍然会交错。

为什么不使用自己的日志文件启动每个实例,并在日志文件名称中使用 ${PID} 将它们分开?IE

 >> "${mylogfile}.${PID}"
Run Code Online (Sandbox Code Playgroud)

编辑

当您希望使用记录器时,请查看手册页:

logger(1) - Linux man page

Name

logger - a shell command interface to the syslog(3) system log module

Synopsis
logger [-isd] [-f file] [-p pri] [-t tag] [-u socket] [message ...]

Description

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

Options:

    -i'         Log the process id of the logger process with each line.
    -s' Log the message to standard error, as well as the system log.
    -f file
        Log the specified file.

.....
Run Code Online (Sandbox Code Playgroud)

这看起来像你想要的。

我希望这有帮助。