【问题标题】:Custom logging from firebase function来自 firebase 功能的自定义日志记录
【发布时间】:2022-01-21 18:11:22
【问题描述】:

我正在尝试按照 this 指南将一些自定义日志记录放入 firebase 函数中。函数本身正在运行,我可以看到传入的数据(它是一个 https 'callable' 函数)。但是,一旦它到达尝试实际写入该日志条目的行,我就会收到“错误:7 PERMISSION_DENIED”

由于 console.log() 调用写入云日志,我假设 firebase 函数可以访问 Cloud Logging。但也许它需要额外的许可?不过,我找不到任何关于应该在该页面上设置的位置的参考。

// Logging, logName, region, functions are provided by the surrounding app

const logging = new Logging()
const log = logging.log(logName)
const METADATA = {
  resource: {
    type: 'cloud_function',
    labels: {
      function_name: 'CustomLog',
      region
    }
  }
};

exports = module.exports = functions.https.onCall(async data => {
  const exVersion = 6
  const exId = data.exId

  console.log('***** exVersion:', exVersion, 'exId:', exId)  // exId from caller
  
  const entry = log.entry(METADATA, data.error)  // data.error from caller
  console.log('METADATA:', METADATA)  // Shows in Logs Explorer
  console.log('entry:', entry)  // Shows in Logs Explorer

  log.write(entry)  // Results in Error: 7 PERMISSION_DENIED

  return {
    exVersion,
    exId,
  }
})

如果我使用 firebase function:shell 从 CLI 运行它,日志条目会正确创建,所以我非常确信代码是正确的。

【问题讨论】:

  • 我在您的 sn-p 中看不到一些重要的东西:const { Logging } = require('@google-cloud/logging'); 以及元数据结构中变量 region 的定义...
  • 见第 1 行的注释——它们都在那里,但在这个例子中没有上下文。代码在本地运行良好。

标签: firebase google-cloud-functions google-cloud-logging


【解决方案1】:

好的,我终于找到了。根据this 的回答,firebase 函数使用的服务帐户是{project-id}@appspot.gserviceaccount.com,在我的项目中,该帐户没有具有“日志编写器”角色。添加该角色可以解决问题。

我觉得很奇怪,firebase 函数不需要该角色来使用console.log() 记录消息,但也许该调用被函数环境拦截,并且日志被写入为不同的服务帐户。它还解释了为什么本地运行的函数能够写入日志,因为它们使用具有完全访问权限的“所有者”服务帐户运行。

【讨论】:

    【解决方案2】:

    根据您已链接的Firebase documentation page

    从函数记录日志的推荐解决方案是使用 记录器 SDK。您可以改为使用标准 JavaScript 日志记录调用,例如 作为console.log 和console.error,但你首先需要一个 修补标准方法以使其正常工作的特殊模块:

    require("firebase-functions/lib/logger/compat");

    一旦您需要记录器兼容性模块,您就可以在代码中正常使用 console.log() 方法。

    因此您可能需要此库,但我不确定这会产生您的"Error: 7 PERMISSION_DENIED 错误,但您也可以尝试一些对社区的某些成员有用的solutions

    【讨论】:

      【解决方案3】:

      您的项目中可能未启用日志记录 API。在这种情况下尝试使用它时会出现权限被拒绝错误。

      这是几个级别,但您链接的指南指向 https://github.com/googleapis/nodejs-logging#before-you-begin,其中包括“Enable the Cloud Logging API”的步骤

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-23
        • 1970-01-01
        • 1970-01-01
        • 2016-08-29
        • 2019-11-15
        • 2023-03-12
        相关资源
        最近更新 更多