TL;DR;
有没有人知道是否可以在Firebase/Google Cloud函数中使用console.log
来使用jsonPayload
属性将条目记录到堆栈驱动程序中,以便我的日志是可搜索的(目前我传递给console.log的任何内容都会被字符串注册到textPayload
中)。
我有一个多模块项目,其中一些代码运行在Firebase Cloud Functions上,一些代码运行在其他环境中,如Google Compute Engine。稍微简化一下,我本质上有一个“核心”模块,然后我将“Cloud -Functions”模块部署到Cloud Functions,将“backend-service”部署到GCE,它们都依赖于“core”等等。
我在我的“核心”模块中使用bunyan进行日志记录,当部署到GCE时,日志记录器是使用“@google-cloud/ logging -bunyan”配置的,所以我的日志记录到Stack Driver中。
旁白:在Google Cloud Functions中使用这种配置会导致Error: Endpoint read failed
出现问题,我认为这是因为函数没有变冷并试图重用死连接,但我不能100%确定真正的原因是什么。
因此,现在我尝试使用console.log(arg)
进行日志记录,其中arg
是一个对象,而不是字符串。我希望这个对象出现在jsonPayload
下的堆栈驱动程序中,但它正在被字符串化并放入textPayload
字段中。
发布于 2019-04-12 06:50:23
我遇到了同样的问题,正如@wtk答案上的评论所说,我想添加复制我可以在下面的代码片段中找到的所有默认云函数日志记录行为,包括execution_id。
至少在使用带有HTTP Trigger
选项的Cloud Functions
时,以下日志为我生成了正确的日志。我还没有测试过Firebase Cloud Functions
// global
const { Logging } = require("@google-cloud/logging");
const logging = new Logging();
const Log = logging.log("cloudfunctions.googleapis.com%2Fcloud-functions");
const LogMetadata = {
severity: "INFO",
type: "cloud_function",
labels: {
function_name: process.env.FUNCTION_NAME,
project: process.env.GCLOUD_PROJECT,
region: process.env.FUNCTION_REGION
}
};
// per request
const data = { foo: "bar" };
const traceId = req.get("x-cloud-trace-context").split("/")[0];
const metadata = {
...LogMetadata,
severity: 'INFO',
trace: `projects/${process.env.GCLOUD_PROJECT}/traces/${traceId}`,
labels: {
execution_id: req.get("function-execution-id")
}
};
Log.write(Log.entry(metadata, data));
发布于 2021-10-13 03:24:25
@wtk答案中的github链接应该更新为:
因为它指的是回答问题时的存储库,并在其中具有以下功能:
// To keep on top of errors, we should raise a verbose error report with Stackdriver rather
// than simply relying on console.error. This will calculate users affected + send you email
// alerts, if you've opted into receiving them.
// [START reporterror]
function reportError(err, context = {}) {
// This is the name of the StackDriver log stream that will receive the log
// entry. This name can be any valid log stream name, but must contain "err"
// in order for the error to be picked up by StackDriver Error Reporting.
const logName = 'errors';
const log = logging.log(logName);
// https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/MonitoredResource
const metadata = {
resource: {
type: 'cloud_function',
labels: {function_name: process.env.FUNCTION_NAME},
},
};
// https://cloud.google.com/error-reporting/reference/rest/v1beta1/ErrorEvent
const errorEvent = {
message: err.stack,
serviceContext: {
service: process.env.FUNCTION_NAME,
resourceType: 'cloud_function',
},
context: context,
};
// Write the error log entry
return new Promise((resolve, reject) => {
log.write(log.entry(metadata, errorEvent), (error) => {
if (error) {
return reject(error);
}
resolve();
});
});
}
// [END reporterror]
https://stackoverflow.com/questions/49185824
复制相似问题