我正在使用Google Cloud虚拟机运行计划在cron上的python脚本,我正在寻找某种方式来检查脚本日志,并将我的脚本运行日志添加到google stackdriver日志中
是否有将python脚本日志添加到google stackdriver日志中,而不是添加到计算引擎中的日志文件中。这种方法的常用方法是什么?请提出建议。
BR / 斯里坎塔
答案 0 :(得分:0)
一个可能的解决方案是假设您的VM具有必要的权限,然后制作一个脚本来读取logs.log
文件并将日志写入Stackdirver。
使用Compute Engine VM实例时,添加云平台访问权限 每个实例的范围。通过创建新实例时 Google Cloud Console,您可以在“身份和API”访问权限中执行此操作 “创建实例”面板的“部分”。使用Compute Engine默认值 服务帐户或您选择的其他服务帐户,然后选择 允许完全访问身份和API访问中的所有Cloud API 部分。无论您选择哪个服务帐户,请确保已 在Cloud的IAM和管理部分中授予Logs Writer角色 控制台。
Setting Up Cloud Logging for Python
例如以下脚本:
import google.cloud.logging
import logging
client = google.cloud.logging.Client()
client.setup_logging()
text = 'Hello, world!'
logging.warning(text)
您可以在“全局”资源类型的python日志下找到日志。
答案 1 :(得分:0)
您可以将Cloud Logging代理与fluentd结合使用,这样就不必更改脚本,并且可以将本地日志文件保留在VM上。
请参见Official documentation安装Cloud Logging Agent
和How to configure it。
在虚拟机上安装代理
curl -sSO https://dl.google.com/cloudagents/install-logging-agent.sh
sudo bash install-logging-agent.sh
为fluentd
内的新本地/etc/google-fluentd/config.d/
日志添加专用配置:
<source>
@type tail
# Format 'none' indicates the log is unstructured (text).
format none
# The path of the log file.
path /tmp/your-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/your-script-log.pos
read_from_head true
# The log tag for this log input.
tag your-script-log
</source>
重新启动代理
sudo service google-fluentd restart
写入您的日志文件: 回声'测试'>> /tmp/your-script-log.log
中检索日志另请参见my answer,但有共同的目标。