我在使用google-cloud / logging时遇到问题。我的目标是写一个每周创建的文件,而我以前已经做到了。但是从昨天开始,我一直收到此错误:
Error: 3 INVALID_ARGUMENT: A monitored resource must be specified for each log entry.
因此,在阅读了有关未自动设置的受监控资源的类似问题之后,我将google-cloud / logging更新为最新版本(5.2.2)。确实解决了该错误,但是更改后,日志未显示在日志查看器中。 我的记录器实用程序代码如下
const { Logging } = require('@google-cloud/logging');
exports.LoggingUtil = class LoggingUtil {
constructor(context){
var LogMetadata = {
severity: "INFO",
type: "gce_instance",
labels: {
function_name: process.env.FUNCTION_NAME,
project: process.env.GCLOUD_PROJECT,
region: process.env.FUNCTION_REGION
}
}
this.metadata = {
LogMetadata,
labels: {
execution_id: `${context.eventId}`
}
}
const logging = new Logging();
this.log = logging.log(this.getWeekStamp());
}
getWeekStamp(){
const environmentName = constants.environment.name;
var d = new Date();
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:1);
date = new Date(d.setDate(diff)).toLocaleDateString('en-US', { day: '2-digit', month: 'short', year: 'numeric'});
date = date.replace(" ", "-");
return `${date.replace(", ","-")}-week-${environmentName}`;
}
write(text){
var entry = this.log.entry(this.metadata, text);
this.log.write(entry);
}
}
我做错了什么?任何帮助表示赞赏help
答案 0 :(得分:0)
我认为您的错误与获取元数据变量的方式有关,因为它正在创建日志查看器无法读取的格式错误的对象。
在方法构造函数中,您将创建类似于以下内容的元数据对象:
{ "LogMetadata":{
"severity":"INFO",
"type":"gce_instance",
"labels":{
"function_name":process.env.FUNCTION_NAME,
"project":process.env.GCLOUD_PROJECT,
"region":process.env.FUNCTION_REGION
}
},
"labels":{
"execution_id":`${context.eventId}`
}}
那不是有效的MonitoredResource,例如,您可以更改代码以创建有效的MonitoredResource
var LogMetadata = {
severity: "INFO",
type: "gce_instance",
labels: {
function_name: process.env.FUNCTION_NAME,
project: process.env.GCLOUD_PROJECT,
region: process.env.FUNCTION_REGION
}
}
this.metadata = LogMetadata
this.metadata.labels["execution_id"] = `${context.eventId}`
示例结果对象
{"severity":"INFO",
"type":"gce_instance",
"labels":{"function_name":process.env.FUNCTION_NAME,
"project":process.env.GCLOUD_PROJECT,
"region": process.env.FUNCTION_REGION,
"execution_id":`${context.eventId}`}
}
此外,您可以选中此example file作为使用nodeJS写入日志的参考。