在GCP中,对于ubuntu-启动脚本日志会自动推送到/var/log/Syslog
,如果长时间后需要的话,由于日志轮换,我们可能会丢失这些日志。有没有办法将这些日志重定向到其他日志文件?我的启动脚本是带有多个命令的简单bash脚本,无法将单个命令的输出重定向到文件。
您可以考虑以下解决方案:
startup-script
内部的输出重定向到专用startup-script.log
目录中的/tmp
文件stackdriver logging
代理startup-script.log
添加特定配置然后,您将能够通过GCP Stackdriver Logging控制台(或通过gcloud
命令来浏览日志)。
Stackdriver Logging将日志仅保留30天。对于较长的保留期,您可以轻松创建sink
以将日志导出到BigQuery表或Cloud Storage存储桶。查看有关导出日志的官方文档:
示例的完整代码startup-script.sh
:
#! /bin/bash
# install gcp logging agent
curl -sSO https://dl.google.com/cloudagents/install-logging-agent.sh
sudo bash install-logging-agent.sh
# setup a configuration for startup-script logs only
cat > /etc/google-fluentd/config.d/startup-script-log.conf <<- EOM
<source>
@type tail
# Format 'none' indicates the log is unstructured (text).
format none
# The path of the log file.
path /tmp/startup-script-log.log
# The path of the position file that records where in the log file
# we have processed already. This is useful when the agent
# restarts.
pos_file /var/lib/google-fluentd/pos/startup-script-log.pos
read_from_head true
# The log tag for this log input.
tag startup-script-log
</source>
EOM
# restart logging agent
sudo service google-fluentd restart
# redirect outputs to dedicated startup-script log
exec &>> /tmp/startup-script-log.log
# your startup-script content
# ...
echo "hello the world"