logging-manager.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. const result = []
  125. for (key in attributes) {
  126. value = attributes[key]
  127. if (value instanceof Error) {
  128. value.reportedToSentry = true
  129. }
  130. return result
  131. }
  132. } catch (err) {
  133. // ignore Raven errors
  134. }
  135. }
  136. },
  137. debug() {
  138. return this.logger.debug.apply(this.logger, arguments)
  139. },
  140. info() {
  141. return this.logger.info.apply(this.logger, arguments)
  142. },
  143. log() {
  144. return this.logger.info.apply(this.logger, arguments)
  145. },
  146. error(attributes, message, ...args) {
  147. if (this.ringBuffer !== null && Array.isArray(this.ringBuffer.records)) {
  148. attributes.logBuffer = this.ringBuffer.records.filter(function(record) {
  149. return record.level !== 50
  150. })
  151. }
  152. this.logger.error(attributes, message, ...Array.from(args))
  153. if (this.raven != null) {
  154. const MAX_ERRORS = 5 // maximum number of errors in 1 minute
  155. const now = new Date()
  156. // have we recently reported an error?
  157. const recentSentryReport = now - this.lastErrorTimeStamp < 60 * 1000
  158. // if so, increment the error count
  159. if (recentSentryReport) {
  160. this.lastErrorCount++
  161. } else {
  162. this.lastErrorCount = 0
  163. this.lastErrorTimeStamp = now
  164. }
  165. // only report 5 errors every minute to avoid overload
  166. if (this.lastErrorCount < MAX_ERRORS) {
  167. // add a note if the rate limit has been hit
  168. const note =
  169. this.lastErrorCount + 1 === MAX_ERRORS ? '(rate limited)' : ''
  170. // report the exception
  171. return this.captureException(attributes, message, `error${note}`)
  172. }
  173. }
  174. },
  175. err() {
  176. return this.error.apply(this, arguments)
  177. },
  178. warn() {
  179. return this.logger.warn.apply(this.logger, arguments)
  180. },
  181. fatal(attributes, message, callback) {
  182. if (callback == null) {
  183. callback = function() {}
  184. }
  185. this.logger.fatal(attributes, message)
  186. if (this.raven != null) {
  187. var cb = function(e) {
  188. // call the callback once after 'logged' or 'error' event
  189. callback()
  190. return (cb = function() {})
  191. }
  192. this.captureException(attributes, message, 'fatal')
  193. this.raven.once('logged', cb)
  194. return this.raven.once('error', cb)
  195. } else {
  196. return callback()
  197. }
  198. },
  199. _setupRingBuffer() {
  200. this.ringBufferSize = parseInt(process.env['LOG_RING_BUFFER_SIZE']) || 0
  201. if (this.ringBufferSize > 0) {
  202. this.ringBuffer = new bunyan.RingBuffer({ limit: this.ringBufferSize })
  203. this.logger.addStream({
  204. level: 'trace',
  205. type: 'raw',
  206. stream: this.ringBuffer
  207. })
  208. } else {
  209. this.ringBuffer = null
  210. }
  211. },
  212. _setupStackdriver() {
  213. const stackdriverEnabled = yn(process.env['STACKDRIVER_LOGGING'])
  214. if (!stackdriverEnabled) {
  215. return
  216. }
  217. const stackdriverClient = new GCPLogging.LoggingBunyan({
  218. logName: this.loggerName,
  219. serviceContext: { service: this.loggerName }
  220. })
  221. this.logger.addStream(stackdriverClient.stream(this.defaultLevel))
  222. },
  223. _setupLogLevelChecker() {
  224. if (this.isProduction) {
  225. // clear interval if already set
  226. if (this.checkInterval) {
  227. clearInterval(this.checkInterval)
  228. }
  229. // check for log level override on startup
  230. this.checkLogLevel()
  231. // re-check log level every minute
  232. this.checkInterval = setInterval(this.checkLogLevel.bind(this), 1000 * 60)
  233. }
  234. }
  235. })
  236. Logger.initialize('default-sharelatex')