logging-manager.js 5.6 KB

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