logging-manager.js 8.0 KB

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