logging-manager.js 7.4 KB

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