logging-manager.js 8.1 KB

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