logging-manager.js 8.4 KB

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