有关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端点)来检查模拟器是否正在运行。如果不存在,则模拟器未运行或者这是生产环境。还要注意使用显式设置的能力,其中传递了projectId
和keyFilename
。
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'
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) {
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