logging-manager.js 7.3 KB

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