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