logging-manager.js 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. const Stream = require('node:stream')
  2. const bunyan = require('bunyan')
  3. const GCPManager = require('./gcp-manager')
  4. const Serializers = require('./serializers')
  5. const {
  6. FileLogLevelChecker,
  7. GCEMetadataLogLevelChecker,
  8. } = require('./log-level-checker')
  9. const LoggingManager = {
  10. /**
  11. * @param {string} name - The name of the logger
  12. */
  13. initialize(name, options = {}) {
  14. this.isProduction =
  15. (process.env.NODE_ENV || '').toLowerCase() === 'production'
  16. const isTest = (process.env.NODE_ENV || '').toLowerCase() === 'test'
  17. this.defaultLevel =
  18. process.env.LOG_LEVEL ||
  19. (this.isProduction ? 'info' : isTest ? 'fatal' : 'debug')
  20. this.loggerName = name
  21. this.logger = bunyan.createLogger({
  22. name,
  23. serializers: {
  24. err: Serializers.err,
  25. error: Serializers.err,
  26. req: Serializers.req,
  27. res: Serializers.res,
  28. },
  29. streams: options.streams ?? [this._getOutputStreamConfig()],
  30. })
  31. this._setupRingBuffer()
  32. this._setupLogLevelChecker()
  33. return this
  34. },
  35. /**
  36. * @param {Record<string, any>|string} attributes - Attributes to log (nice serialization for err, req, res)
  37. * @param {string} [message] - Optional message
  38. * @signature `debug(attributes, message)`
  39. * @signature `debug(message)`
  40. */
  41. debug(attributes, message, ...args) {
  42. return this.logger.debug(attributes, message, ...args)
  43. },
  44. /**
  45. * @param {Record<string, any>|string} attributes - Attributes to log (nice serialization for err, req, res)
  46. * @param {string} [message]
  47. * @signature `info(attributes, message)`
  48. * @signature `info(message)`
  49. */
  50. info(attributes, message, ...args) {
  51. return this.logger.info(attributes, message, ...args)
  52. },
  53. /**
  54. * @param {Record<string, any>} attributes - Attributes to log (nice serialization for err, req, res)
  55. * @param {string} [message]
  56. */
  57. error(attributes, message, ...args) {
  58. if (this.ringBuffer !== null && Array.isArray(this.ringBuffer.records)) {
  59. attributes.logBuffer = this.ringBuffer.records.filter(function (record) {
  60. return record.level !== 50
  61. })
  62. }
  63. this.logger.error(attributes, message, ...Array.from(args))
  64. },
  65. /**
  66. * Alias to the error method.
  67. * @param {Record<string, any>} attributes - Attributes to log (nice serialization for err, req, res)
  68. * @param {string} [message]
  69. */
  70. err(attributes, message, ...args) {
  71. return this.error(attributes, message, ...args)
  72. },
  73. /**
  74. * @param {Record<string, any>|string} attributes - Attributes to log (nice serialization for err, req, res)
  75. * @param {string} [message]
  76. * @signature `warn(attributes, message)`
  77. * @signature `warn(message)`
  78. */
  79. warn(attributes, message, ...args) {
  80. return this.logger.warn(attributes, message, ...args)
  81. },
  82. /**
  83. * @param {Record<string, any>} attributes - Attributes to log (nice serialization for err, req, res)
  84. * @param {string} [message]
  85. */
  86. fatal(attributes, message) {
  87. this.logger.fatal(attributes, message)
  88. },
  89. _getOutputStreamConfig() {
  90. switch (process.env.LOGGING_FORMAT) {
  91. case 'gke': {
  92. const stream = new Stream.Writable({
  93. objectMode: true,
  94. write(entry, encoding, callback) {
  95. const gcpEntry = GCPManager.convertLogEntry(entry)
  96. // eslint-disable-next-line no-console
  97. console.log(JSON.stringify(gcpEntry, bunyan.safeCycles()))
  98. setImmediate(callback)
  99. },
  100. })
  101. return { level: this.defaultLevel, type: 'raw', stream }
  102. }
  103. case 'gce': {
  104. const { LoggingBunyan } = require('@google-cloud/logging-bunyan')
  105. return new LoggingBunyan({
  106. logName: this.loggerName,
  107. serviceContext: { service: this.loggerName },
  108. }).stream(this.defaultLevel)
  109. }
  110. default: {
  111. return { level: this.defaultLevel, stream: process.stdout }
  112. }
  113. }
  114. },
  115. _setupRingBuffer() {
  116. this.ringBufferSize = parseInt(process.env.LOG_RING_BUFFER_SIZE) || 0
  117. if (this.ringBufferSize > 0) {
  118. this.ringBuffer = new bunyan.RingBuffer({ limit: this.ringBufferSize })
  119. this.logger.addStream({
  120. level: 'trace',
  121. type: 'raw',
  122. stream: this.ringBuffer,
  123. })
  124. } else {
  125. this.ringBuffer = null
  126. }
  127. },
  128. _setupLogLevelChecker() {
  129. const logLevelSource = (
  130. process.env.LOG_LEVEL_SOURCE || 'file'
  131. ).toLowerCase()
  132. if (this.logLevelChecker) {
  133. this.logLevelChecker.stop()
  134. this.logLevelChecker = null
  135. }
  136. if (this.isProduction) {
  137. switch (logLevelSource) {
  138. case 'file':
  139. this.logLevelChecker = new FileLogLevelChecker(
  140. this.logger,
  141. this.defaultLevel
  142. )
  143. break
  144. case 'gce_metadata':
  145. this.logLevelChecker = new GCEMetadataLogLevelChecker(
  146. this.logger,
  147. this.defaultLevel
  148. )
  149. break
  150. case 'none':
  151. break
  152. default:
  153. // eslint-disable-next-line no-console
  154. console.log(`Unrecognised log level source: ${logLevelSource}`)
  155. }
  156. if (this.logLevelChecker) {
  157. this.logLevelChecker.start()
  158. }
  159. }
  160. },
  161. }
  162. LoggingManager.initialize('default')
  163. function handleWarning(err) {
  164. LoggingManager.warn({ err }, 'Warning details')
  165. }
  166. process.on('warning', handleWarning)
  167. LoggingManager.removeWarningHandler = () => {
  168. process.off('warning', handleWarning)
  169. }
  170. module.exports = LoggingManager