logging-manager.js 8.3 KB

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