logging-manager.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. const bunyan = require('bunyan')
  2. const fs = require('fs')
  3. const yn = require('yn')
  4. const OError = require('@overleaf/o-error')
  5. const GCPLogging = require('@google-cloud/logging-bunyan')
  6. // bunyan error serializer
  7. const errSerializer = function (err) {
  8. if (!err || !err.stack) {
  9. return err
  10. }
  11. return {
  12. message: err.message,
  13. name: err.name,
  14. stack: OError.getFullStack(err),
  15. info: OError.getFullInfo(err),
  16. code: err.code,
  17. signal: err.signal
  18. }
  19. }
  20. const Logger = (module.exports = {
  21. initialize(name) {
  22. this.isProduction =
  23. (process.env.NODE_ENV || '').toLowerCase() === 'production'
  24. this.defaultLevel =
  25. process.env.LOG_LEVEL || (this.isProduction ? 'warn' : 'debug')
  26. this.loggerName = name
  27. this.logger = bunyan.createLogger({
  28. name,
  29. serializers: {
  30. err: errSerializer,
  31. req: bunyan.stdSerializers.req,
  32. res: bunyan.stdSerializers.res
  33. },
  34. streams: [{ level: this.defaultLevel, stream: process.stdout }]
  35. })
  36. this._setupRingBuffer()
  37. this._setupStackdriver()
  38. this._setupLogLevelChecker()
  39. return this
  40. },
  41. checkLogLevel() {
  42. fs.readFile('/logging/tracingEndTime', (error, end) => {
  43. if (error || !end) {
  44. this.logger.level(this.defaultLevel)
  45. return
  46. }
  47. if (parseInt(end) > Date.now()) {
  48. this.logger.level('trace')
  49. } else {
  50. this.logger.level(this.defaultLevel)
  51. }
  52. })
  53. },
  54. initializeErrorReporting(sentryDsn, options) {
  55. const raven = require('raven')
  56. this.raven = new raven.Client(sentryDsn, options)
  57. this.lastErrorTimeStamp = 0 // for rate limiting on sentry reporting
  58. this.lastErrorCount = 0
  59. },
  60. captureException(attributes, message, level) {
  61. // handle case of logger.error "message"
  62. let key, value
  63. if (typeof attributes === 'string') {
  64. attributes = { err: new Error(attributes) }
  65. }
  66. // extract any error object
  67. let error = attributes.err || attributes.error
  68. // avoid reporting errors twice
  69. for (key in attributes) {
  70. value = attributes[key]
  71. if (value instanceof Error && value.reportedToSentry) {
  72. return
  73. }
  74. }
  75. // include our log message in the error report
  76. if (error == null) {
  77. if (typeof message === 'string') {
  78. error = { message }
  79. }
  80. } else if (message != null) {
  81. attributes.description = message
  82. }
  83. // report the error
  84. if (error != null) {
  85. // capture attributes and use *_id objects as tags
  86. const tags = {}
  87. const extra = {}
  88. for (key in attributes) {
  89. value = attributes[key]
  90. if (key.match(/_id/) && typeof value === 'string') {
  91. tags[key] = value
  92. }
  93. extra[key] = value
  94. }
  95. // capture req object if available
  96. const { req } = attributes
  97. if (req != null) {
  98. extra.req = {
  99. method: req.method,
  100. url: req.originalUrl,
  101. query: req.query,
  102. headers: req.headers,
  103. ip: req.ip
  104. }
  105. }
  106. // recreate error objects that have been converted to a normal object
  107. if (!(error instanceof Error) && typeof error === 'object') {
  108. const newError = new Error(error.message)
  109. for (key of Object.keys(error || {})) {
  110. value = error[key]
  111. newError[key] = value
  112. }
  113. error = newError
  114. }
  115. // filter paths from the message to avoid duplicate errors in sentry
  116. // (e.g. errors from `fs` methods which have a path attribute)
  117. try {
  118. if (error.path) {
  119. error.message = error.message.replace(` '${error.path}'`, '')
  120. }
  121. // send the error to sentry
  122. this.raven.captureException(error, { tags, extra, level })
  123. // put a flag on the errors to avoid reporting them multiple times
  124. for (key in attributes) {
  125. value = attributes[key]
  126. if (value instanceof Error) {
  127. value.reportedToSentry = true
  128. }
  129. }
  130. } catch (err) {
  131. // ignore Raven errors
  132. }
  133. }
  134. },
  135. debug() {
  136. return this.logger.debug.apply(this.logger, arguments)
  137. },
  138. info() {
  139. return this.logger.info.apply(this.logger, arguments)
  140. },
  141. log() {
  142. return this.logger.info.apply(this.logger, arguments)
  143. },
  144. error(attributes, message, ...args) {
  145. if (this.ringBuffer !== null && Array.isArray(this.ringBuffer.records)) {
  146. attributes.logBuffer = this.ringBuffer.records.filter(function (record) {
  147. return record.level !== 50
  148. })
  149. }
  150. this.logger.error(attributes, message, ...Array.from(args))
  151. if (this.raven != null) {
  152. const MAX_ERRORS = 5 // maximum number of errors in 1 minute
  153. const now = new Date()
  154. // have we recently reported an error?
  155. const recentSentryReport = now - this.lastErrorTimeStamp < 60 * 1000
  156. // if so, increment the error count
  157. if (recentSentryReport) {
  158. this.lastErrorCount++
  159. } else {
  160. this.lastErrorCount = 0
  161. this.lastErrorTimeStamp = now
  162. }
  163. // only report 5 errors every minute to avoid overload
  164. if (this.lastErrorCount < MAX_ERRORS) {
  165. // add a note if the rate limit has been hit
  166. const note =
  167. this.lastErrorCount + 1 === MAX_ERRORS ? '(rate limited)' : ''
  168. // report the exception
  169. return this.captureException(attributes, message, `error${note}`)
  170. }
  171. }
  172. },
  173. err() {
  174. return this.error.apply(this, arguments)
  175. },
  176. warn() {
  177. return this.logger.warn.apply(this.logger, arguments)
  178. },
  179. fatal(attributes, message, callback) {
  180. if (callback == null) {
  181. callback = function () {}
  182. }
  183. this.logger.fatal(attributes, message)
  184. if (this.raven != null) {
  185. var cb = function (e) {
  186. // call the callback once after 'logged' or 'error' event
  187. callback()
  188. return (cb = function () {})
  189. }
  190. this.captureException(attributes, message, 'fatal')
  191. this.raven.once('logged', cb)
  192. return this.raven.once('error', cb)
  193. } else {
  194. return callback()
  195. }
  196. },
  197. _setupRingBuffer() {
  198. this.ringBufferSize = parseInt(process.env.LOG_RING_BUFFER_SIZE) || 0
  199. if (this.ringBufferSize > 0) {
  200. this.ringBuffer = new bunyan.RingBuffer({ limit: this.ringBufferSize })
  201. this.logger.addStream({
  202. level: 'trace',
  203. type: 'raw',
  204. stream: this.ringBuffer
  205. })
  206. } else {
  207. this.ringBuffer = null
  208. }
  209. },
  210. _setupStackdriver() {
  211. const stackdriverEnabled = yn(process.env.STACKDRIVER_LOGGING)
  212. if (!stackdriverEnabled) {
  213. return
  214. }
  215. const stackdriverClient = new GCPLogging.LoggingBunyan({
  216. logName: this.loggerName,
  217. serviceContext: { service: this.loggerName }
  218. })
  219. this.logger.addStream(stackdriverClient.stream(this.defaultLevel))
  220. },
  221. _setupLogLevelChecker() {
  222. if (this.isProduction) {
  223. // clear interval if already set
  224. if (this.checkInterval) {
  225. clearInterval(this.checkInterval)
  226. }
  227. // check for log level override on startup
  228. this.checkLogLevel()
  229. // re-check log level every minute
  230. this.checkInterval = setInterval(this.checkLogLevel.bind(this), 1000 * 60)
  231. }
  232. }
  233. })
  234. Logger.initialize('default-sharelatex')