首页 > 解决方案 > Is there any way to output logs using log4js on Cloud Functions?

问题描述

I'm using GCP's cloud function. What I want to achieve is to output logs by log4js.

I know and have tried that using console.xxx() works well.

Environment: - Google Cloud Functions - Functions-framework - nodejs10 as Runtime

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
};

Thanks in advance!

标签: google-cloud-functionslog4js-node

解决方案


根据官方文档链接

Cloud Logging 是 Google Cloud 中 Google Cloud 产品操作套件的一部分。它包括日志存储、称为日志查看器的用户界面和以编程方式管理日志的 API。

还有自定义 StackDriver 日志

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。


推荐阅读