如何将服务的前缀/标签添加到主管标准输出输出

Kon*_*tin 8 logging supervisord docker

当我必须在一个图像中运行多个服务(例如 postfix 和其他邮件服务)时,我在 docker 图像中使用主管。当我将所有服务的 stdout/stderr 重定向到主管并且主管也登录到 stdout/stderr 时,我希望在控制台上的实际日志输出前面有一个前缀/标签,以了解哪个日志来自哪个服务。我找不到任何配置设置,但也许你知道一种方法。

以下是 Foreman 的示例: 工头日志输出

小智 7

@flocki 感谢您的精彩回答!下面是一个稍微更完整的示例:

[program:nginx]
command=/usr/local/bin/prefix-log /usr/sbin/nginx -g "daemon off; error_log /dev/stderr info;"
autostart=true
autorestart=true
priority=10
stdout_events_enabled=true
stderr_events_enabled=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
stopsignal=QUIT
Run Code Online (Sandbox Code Playgroud)

前缀日志:

#!/usr/bin/env bash
# setup fd-3 to point to the original stdout
exec 3>&1
# setup fd-4 to point to the original stderr
exec 4>&2

# get the prefix from SUPERVISOR_PROCESS_NAME environement variable
printf -v PREFIX "%-10.10s" ${SUPERVISOR_PROCESS_NAME}

# reassign stdout and stderr to a preprocessed and redirected to the original stdout/stderr (3 and 4) we have create eralier
exec 1> >( perl -ne '$| = 1; print "'"${PREFIX}"' | $_"' >&3)
exec 2> >( perl -ne '$| = 1; print "'"${PREFIX}"' | $_"' >&4)

# from here on everthing that outputs to stdout/stderr will be go through the perl script

exec "$@"
Run Code Online (Sandbox Code Playgroud)


小智 4

我最近遇到了同样的问题,无法弄清楚supervisor-stdout。这是我所做的:

在 bash 中,您可以使用I/O 重定向进程替换stdout来通过另一个进程进行管道传输stderr

    #!/usr/bin/env bash
    # setup fd-3 to point to the original stdout
    exec 3>&1
    # setup fd-4 to point to the original stderr
    exec 4>&2

    # get the prefix from SUPERVISOR_PROCESS_NAME environement variable
    printf -v PREFIX "%-10.10s" ${SUPERVISOR_PROCESS_NAME}

    # reassign stdout and stderr to a preprocessed and redirected to the original stdout/stderr (3 and 4) we have create eralier
    exec 1> >( perl -ne '$| = 1; print "'"${PREFIX}"' | $_"' >&3)
    exec 2> >( perl -ne '$| = 1; print "'"${PREFIX}"' | $_"' >&4)
    # from here on everthing that outputs to stdout/stderr will be go through the perl script
    echo "I will be prefixed"
    # don't forget to use exec 
Run Code Online (Sandbox Code Playgroud)

现在您可以设置 Supervisor 使用 stdout 和 stderr 进行日志记录:

    stdout_logfile=/dev/stdout
    stdout_logfile_maxbytes=0
    stderr_logfile=/dev/stderr
    stderr_logfile_maxbytes=0
Run Code Online (Sandbox Code Playgroud)

作为命令,使用设置 I/O 重定向的 bash 脚本。