logging-manager.js 8.1 KB

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