logging-manager.coffee 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. bunyan = require('bunyan')
  2. module.exports = Logger =
  3. initialize: (name) ->
  4. @logger = bunyan.createLogger
  5. name: name
  6. serializers: bunyan.stdSerializers
  7. return @
  8. initializeErrorReporting: (sentry_dsn, options) ->
  9. raven = require "raven"
  10. @raven = new raven.Client(sentry_dsn, options)
  11. captureException: (attributes, message, level) ->
  12. # handle case of logger.error "message"
  13. if typeof attributes is 'string'
  14. attributes = {err: attributes}
  15. # extract any error object
  16. error = attributes.err or attributes.error
  17. # use our log message as the title when available
  18. if not error?
  19. error = {message: message} if typeof message is 'string'
  20. else if message?
  21. error.exception = error.message
  22. error.message = message
  23. # report the error
  24. if error?
  25. # capture attributes and use *_id objects as tags
  26. tags = {}
  27. extra = {}
  28. for key, value of attributes
  29. tags[key] = value if key.match(/_id/) and typeof value == 'string'
  30. extra[key] = value
  31. # capture req object if available
  32. req = attributes.req
  33. if req?
  34. extra.req =
  35. method: req.method
  36. url: req.originalUrl
  37. query: req.query
  38. headers: req.headers
  39. ip: req.ip
  40. # recreate error objects that have been converted to a normal object
  41. if !(error instanceof Error) and typeof error is "object"
  42. newError = new Error(error.message)
  43. for own key, value of error
  44. newError[key] = value
  45. error = newError
  46. # send the error to sentry
  47. @raven.captureException(error, {tags: tags, extra: extra, level: level})
  48. info : ()->
  49. @logger.info.apply(@logger, arguments)
  50. log : ()->
  51. @logger.info.apply(@logger, arguments)
  52. error: (attributes, message, args...)->
  53. @logger.error(attributes, message, args...)
  54. @captureException(attributes, message, "error") if @raven?
  55. err: () ->
  56. @error.apply(this, arguments)
  57. warn: ()->
  58. @logger.warn.apply(@logger, arguments)
  59. fatal: (attributes, message, callback) ->
  60. @logger.fatal(attributes, message)
  61. if @raven?
  62. cb = (e) -> # call the callback once after 'logged' or 'error' event
  63. callback()
  64. cb = () ->
  65. @captureException(attributes, message, "fatal")
  66. @raven.once 'logged', cb
  67. @raven.once 'error', cb
  68. else
  69. callback()
  70. Logger.initialize("default-sharelatex")