【问题标题】:Is there any way to output logs using log4js on Cloud Functions?有没有办法在 Cloud Functions 上使用 log4js 输出日志?
【发布时间】:2020-06-19 04:50:46
【问题描述】:

我正在使用 GCP 的云功能。我想要实现的是通过log4js输出日志。

我知道并尝试过使用 console.xxx() 效果很好。

环境: - 谷歌云功能 - 功能框架 - nodejs10 作为运行时

logger.js

const log4js = require('log4js');

const logger = exports = module.exports = {};

log4js.configure({
  appenders: {
    out: { type: 'console' },
    trail: {
      type: 'dateFile',
      filename: './logs/trail',
      pattern: '-yyyy-MMdd-hh.log',
      alwaysIncludePattern: true
    }
  },
  categories: {
    default: { appenders: [ 'out' ], level: 'info' },
    trail: { appenders: [ 'trail' ], level: 'DEBUG' }
  }
})

logger.trail = log4js.getLogger('trail')

index.js

const { logger } = require('./logger');

exports.spTest = (pubSubEvent, context) => {
  console.log('console.log should appear'); // => properly logged
  logger.trail.error('logger should appear'); => doesn't show up
};

提前致谢!

【问题讨论】:

    标签: google-cloud-functions log4js-node


    【解决方案1】:

    根据官方文档link

    Cloud Logging 是 Google Cloud 运营套件的一部分 谷歌云中的产品。它包括存储日志、用户 称为日志查看器的界面,以及用于管理日志的 API 以编程方式。

    还有Custom StackDriver logs

    Cloud Functions 日志由 StackDriver Logging 提供支持。您可以使用 用于 Node.js 的 StackDriver Logging 库,用于记录事件 结构化数据,便于分析和监控。

    
    const { Logging } = require('@google-cloud/logging');
    
    // ...
    
    // Instantiate the StackDriver Logging SDK. The project ID will
    // be automatically inferred from the Cloud Functions environment.
    const logging = new Logging();
    const log = logging.log('my-custom-log-name');
    
    // This metadata is attached to each log entry. This specifies a fake
    // Cloud Function called 'Custom Metrics' in order to make your custom
    // log entries appear in the Cloud Functions logs viewer.
    const METADATA = {
      resource: {
        type: 'cloud_function',
        labels: {
          function_name: 'CustomMetrics',
          region: 'us-central1'
        }
      }
    };
    
    // ...
    
    // Data to write to the log. This can be a JSON object with any properties
    // of the event you want to record.
    const data = {
      event: 'my-event',
      value: 'foo-bar-baz',
    
      // Optional 'message' property will show up in the Firebase
      // console and other human-readable logging surfaces
      message: 'my-event: foo-bar-baz'
    };
    
    // Write to the log. The log.write() call returns a Promise if you want to
    // make sure that the log was written successfully.
    const entry = log.entry(METADATA, data);
    log.write(entry);index.js
    
    

    因此,我认为您不能在 Cloud Functions 上使用 log4js。

    【讨论】:

    • 啊,这个SDK还是可以管理的,够了!其实这就是我需要的。我很感激!
    • 如果我的回答对您有帮助,请接受它以提高社区的知名度。
    猜你喜欢
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    • 2017-11-09
    • 2017-10-29
    • 1970-01-01
    相关资源
    最近更新 更多