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