有什么方法可以在 Cloud Functions 上使用 log4js 输出日志吗?

Is there any way to output logs using log4js on Cloud Functions?

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

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

环境: - Google 云功能 - 功能框架 - 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
};

提前致谢!

根据官方文档link:

Cloud Logging is part of the Google Cloud's operations suite of products in Google Cloud. It includes storage for logs, a user interface called the Logs Viewer, and an API to manage logs programmatically.

还有Custom StackDriver logs

Cloud Functions logs are backed by StackDriver Logging. You can use the StackDriver Logging library for Node.js to log events with structured data, enabling easier analysis and monitoring.


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。