Firebase函数:在Stackdriver控制台中使用Winston进行日志记录

5
我无法使winston记录器将日志写入stackdriver控制台。 我将我的函数部署为Google Firebase函数(使用firebase deploy)。console记录正常工作,但我们在项目中不使用这种工具。
我尝试过:

请提供建议... 我已经厌倦了实验(每次重新部署都需要时间)

3个回答

3

最后我做的事情是实现自定义传输,实际上在内部调用console.log。这很有帮助。

const winston = require('winston');
const util = require('util');
const ClassicConsoleLoggerTransport = winston.transports.CustomLogger = function (options) {
    options = options || {};
    this.name = 'ClassicConsoleLoggerTransport';
    this.level = options.level || 'info';
    // Configure your storage backing as you see fit
};
util.inherits(ClassicConsoleLoggerTransport, winston.Transport);

ClassicConsoleLoggerTransport.prototype.log = function (level, msg, meta, callback) {
    let args = [msg, '---', meta];
    switch (level) {
        case 'verbose':
        case 'debug':
            console.log.apply(null, args);
            break;
        case 'notice':
        case 'info':
            console.info.apply(null, args);
            break;
        case 'warn':
        case 'warning':
            console.warn.apply(null, args);
            break;
        case 'error':
        case 'crit':
        case 'alert':
        case 'emerg':
            console.error.apply(null, args);
            break;
        default:
            console.log.apply(null, args);
    }
    callback(null, true);
};

你能添加必需的文件并说明如何在Github中使用Gist吗? - Tarun

2
Winston的默认Console传输方式失败了,因为它使用console._stdout.write,而Firebase Functions不接受这种方式。
现在有一个适用于Stackdriver的Google Cloud传输包(@google-cloud/logging-winston)可供尝试。如果您正在使用Winston 3,则需要node ^8.11.2版本。

0

有关node.js winston设置的文档在这里这里

我已经在下面添加了完整的logger.js设置。

重要的部分是:

const format = winston.format.combine(winston.format.colorize({ all: true }))
const console = new winston.transports.Console({ format: winston.format.combine(format) })

const options = this.#explicitSetup ? { projectId: appConfig.firebase.options.projectId, keyFilename: `${rootDirname}/service-account-file.json` } : {}
const loggingWinston = new LoggingWinston(options)

const transports = emulators ? [console] : [console, loggingWinston]

this.#logger = winston.createLogger({
  level: this.#defaultLevel,
  transports
})

基本上,如果模拟器正在运行,则使用控制台记录器,否则使用控制台记录器和堆栈驱动程序传输。您可以通过在本地主机上ping函数端点(例如您创建的/ping端点)来检查模拟器是否正在运行。如果不存在,则模拟器未运行或者这是生产环境。还要注意使用显式设置的能力,其中传递了projectIdkeyFilename

keyFilename的JSON文件可以在此处创建:

https://cloud.google.com/docs/authentication/getting-started

以下是我的完整logger.js代码,如果有帮助的话:

import winston from 'winston'
import { LoggingWinston } from '@google-cloud/logging-winston'
import { appConfig } from '../app-config.js'
import { rootDirname } from './root-dirname.js'
import { isObjectLike } from 'lodash-es'

// https://cloud.google.com/logging/docs/setup/nodejs

export class Logger {

  #logger
  #defaultLevel = 'debug'
  #explicitSetup = false

  constructor() {
    this.error = this.error.bind(this)
    this.warn = this.warn.bind(this)
    this.info = this.info.bind(this)
    this.debug = this.debug.bind(this)
    this.log = this.log.bind(this)
  }

  init(emulators) {

    // https://dev59.com/qlUK5IYBdhLWcg3w_z60#64173978
    winston.addColors({
      error: 'red',
      warn: 'yellow',
      info: 'bold cyan',
      debug: 'bold green'
    })

    const format = winston.format.combine(winston.format.colorize({ all: true }))
    const console = new winston.transports.Console({ format: winston.format.combine(format) })

    const options = this.#explicitSetup ? { projectId: appConfig.firebase.options.projectId, keyFilename: `${rootDirname}/service-account-file.json` } : {}
    const loggingWinston = new LoggingWinston(options)

    const transports = emulators ? [console] : [console, loggingWinston]

    this.#logger = winston.createLogger({
      level: this.#defaultLevel,
      transports
    })
  }

  error(...args) {
    this.#logger.error(this.#argsToString(args))
  }

  warn(...args) {
    this.#logger.warn(this.#argsToString(args))
  }

  info(...args) {
    this.#logger.info(this.#argsToString(args))
  }

  debug(...args) {
    this.#logger.debug(this.#argsToString(args))
  }

  log(...args) {
    this.#logger[this.#defaultLevel](this.#argsToString(args))
  }

  #argsToString(args) {
    return args.map(arg => {
      const str = isObjectLike(arg) ? JSON.stringify(arg) : arg.toString()
      return str.trim()
    }).join(' \u2022\u2022 ')
  }
}

const blogger = new Logger()
export const logger = blogger

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接