loggingManagerTests.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. const SandboxedModule = require('sandboxed-module')
  2. const bunyan = require('bunyan')
  3. const chai = require('chai')
  4. const path = require('path')
  5. const sinon = require('sinon')
  6. const sinonChai = require('sinon-chai')
  7. chai.use(sinonChai)
  8. chai.should()
  9. const expect = chai.expect
  10. const modulePath = path.join(__dirname, '../../logging-manager.js')
  11. describe('LoggingManager', function () {
  12. beforeEach(function () {
  13. this.start = Date.now()
  14. this.clock = sinon.useFakeTimers(this.start)
  15. this.captureException = sinon.stub()
  16. this.bunyanLogger = {
  17. addStream: sinon.stub(),
  18. debug: sinon.stub(),
  19. error: sinon.stub(),
  20. fatal: sinon.stub(),
  21. info: sinon.stub(),
  22. level: sinon.stub(),
  23. warn: sinon.stub()
  24. }
  25. this.Sentry = {
  26. init: sinon.stub(),
  27. captureException: this.captureException
  28. }
  29. this.fetchResponse = {
  30. text: sinon.stub().resolves(''),
  31. status: 200,
  32. ok: true
  33. }
  34. this.Bunyan = {
  35. createLogger: sinon.stub().returns(this.bunyanLogger),
  36. RingBuffer: bunyan.RingBuffer,
  37. stdSerializers: {
  38. req: sinon.stub(),
  39. res: sinon.stub()
  40. }
  41. }
  42. this.Fetch = sinon.stub().resolves(this.fetchResponse)
  43. this.Fs = {
  44. readFile: sinon.stub(),
  45. promises: {
  46. readFile: sinon.stub()
  47. }
  48. }
  49. this.stackdriverStreamConfig = { stream: 'stackdriver' }
  50. this.stackdriverClient = {
  51. stream: sinon.stub().returns(this.stackdriverStreamConfig)
  52. }
  53. this.GCPLogging = {
  54. LoggingBunyan: sinon.stub().returns(this.stackdriverClient)
  55. }
  56. this.LoggingManager = SandboxedModule.require(modulePath, {
  57. globals: { console, process },
  58. requires: {
  59. bunyan: this.Bunyan,
  60. '@sentry/node': this.Sentry,
  61. 'node-fetch': this.Fetch,
  62. fs: this.Fs,
  63. '@google-cloud/logging-bunyan': this.GCPLogging
  64. }
  65. })
  66. this.loggerName = 'test'
  67. this.logger = this.LoggingManager.initialize(this.loggerName)
  68. this.logger.initializeErrorReporting('test_dsn')
  69. })
  70. afterEach(function () {
  71. this.clock.restore()
  72. })
  73. describe('initialize', function () {
  74. beforeEach(function () {
  75. this.checkLogLevelStub = sinon
  76. .stub(this.LoggingManager, 'checkLogLevel')
  77. .resolves('')
  78. this.Bunyan.createLogger.reset()
  79. })
  80. afterEach(function () {
  81. this.checkLogLevelStub.restore()
  82. })
  83. describe('not in production', function () {
  84. beforeEach(function () {
  85. this.logger = this.LoggingManager.initialize(this.loggerName)
  86. })
  87. it('should default to log level debug', function () {
  88. this.Bunyan.createLogger.firstCall.args[0].streams[0].level.should.equal(
  89. 'debug'
  90. )
  91. })
  92. it('should not run checkLogLevel', function () {
  93. this.checkLogLevelStub.should.not.have.been.called
  94. })
  95. })
  96. describe('in production', function () {
  97. beforeEach(function () {
  98. process.env.NODE_ENV = 'production'
  99. this.logger = this.LoggingManager.initialize(this.loggerName)
  100. })
  101. afterEach(() => delete process.env.NODE_ENV)
  102. it('should default to log level warn', function () {
  103. this.Bunyan.createLogger.firstCall.args[0].streams[0].level.should.equal(
  104. 'warn'
  105. )
  106. })
  107. describe('logLevelSource file', function () {
  108. it('should run checkLogLevel', function () {
  109. this.checkLogLevelStub.should.have.been.calledOnce
  110. })
  111. describe('after 1 minute', () =>
  112. it('should run checkLogLevel again', function () {
  113. this.clock.tick(61 * 1000)
  114. this.checkLogLevelStub.should.have.been.calledTwice
  115. }))
  116. describe('after 2 minutes', () =>
  117. it('should run checkLogLevel again', function () {
  118. this.clock.tick(121 * 1000)
  119. this.checkLogLevelStub.should.have.been.calledThrice
  120. }))
  121. })
  122. })
  123. describe('when LOG_LEVEL set in env', function () {
  124. beforeEach(function () {
  125. process.env.LOG_LEVEL = 'trace'
  126. this.LoggingManager.initialize()
  127. })
  128. afterEach(() => delete process.env.LOG_LEVEL)
  129. it('should use custom log level', function () {
  130. this.Bunyan.createLogger.firstCall.args[0].streams[0].level.should.equal(
  131. 'trace'
  132. )
  133. })
  134. })
  135. })
  136. describe('bunyan logging', function () {
  137. beforeEach(function () {
  138. this.logArgs = [{ foo: 'bar' }, 'foo', 'bar']
  139. })
  140. it('should log debug', function () {
  141. this.logger.debug(this.logArgs)
  142. this.bunyanLogger.debug.should.have.been.calledWith(this.logArgs)
  143. })
  144. it('should log error', function () {
  145. this.logger.error(this.logArgs)
  146. this.bunyanLogger.error.should.have.been.calledWith(this.logArgs)
  147. })
  148. it('should log fatal', function () {
  149. this.logger.fatal(this.logArgs)
  150. this.bunyanLogger.fatal.should.have.been.calledWith(this.logArgs)
  151. })
  152. it('should log info', function () {
  153. this.logger.info(this.logArgs)
  154. this.bunyanLogger.info.should.have.been.calledWith(this.logArgs)
  155. })
  156. it('should log warn', function () {
  157. this.logger.warn(this.logArgs)
  158. this.bunyanLogger.warn.should.have.been.calledWith(this.logArgs)
  159. })
  160. it('should log err', function () {
  161. this.logger.err(this.logArgs)
  162. this.bunyanLogger.error.should.have.been.calledWith(this.logArgs)
  163. })
  164. it('should log log', function () {
  165. this.logger.log(this.logArgs)
  166. this.bunyanLogger.info.should.have.been.calledWith(this.logArgs)
  167. })
  168. })
  169. describe('logger.error', function () {
  170. it('should report a single error to sentry', function () {
  171. this.logger.error({ foo: 'bar' }, 'message')
  172. this.captureException.called.should.equal(true)
  173. })
  174. it('should report the same error to sentry only once', function () {
  175. const error1 = new Error('this is the error')
  176. this.logger.error({ foo: error1 }, 'first message')
  177. this.logger.error({ bar: error1 }, 'second message')
  178. this.captureException.callCount.should.equal(1)
  179. })
  180. it('should report two different errors to sentry individually', function () {
  181. const error1 = new Error('this is the error')
  182. const error2 = new Error('this is the error')
  183. this.logger.error({ foo: error1 }, 'first message')
  184. this.logger.error({ bar: error2 }, 'second message')
  185. this.captureException.callCount.should.equal(2)
  186. })
  187. it('should remove the path from fs errors', function () {
  188. const fsError = new Error(
  189. "Error: ENOENT: no such file or directory, stat '/tmp/3279b8d0-da10-11e8-8255-efd98985942b'"
  190. )
  191. fsError.path = '/tmp/3279b8d0-da10-11e8-8255-efd98985942b'
  192. this.logger.error({ err: fsError }, 'message')
  193. this.captureException
  194. .calledWith(
  195. sinon.match.has(
  196. 'message',
  197. 'Error: ENOENT: no such file or directory, stat'
  198. )
  199. )
  200. .should.equal(true)
  201. })
  202. it('for multiple errors should only report a maximum of 5 errors to sentry', function () {
  203. this.logger.error({ foo: 'bar' }, 'message')
  204. this.logger.error({ foo: 'bar' }, 'message')
  205. this.logger.error({ foo: 'bar' }, 'message')
  206. this.logger.error({ foo: 'bar' }, 'message')
  207. this.logger.error({ foo: 'bar' }, 'message')
  208. this.logger.error({ foo: 'bar' }, 'message')
  209. this.logger.error({ foo: 'bar' }, 'message')
  210. this.logger.error({ foo: 'bar' }, 'message')
  211. this.logger.error({ foo: 'bar' }, 'message')
  212. this.captureException.callCount.should.equal(5)
  213. })
  214. it('for multiple errors with a minute delay should report 10 errors to sentry', function () {
  215. // the first five errors should be reported to sentry
  216. this.logger.error({ foo: 'bar' }, 'message')
  217. this.logger.error({ foo: 'bar' }, 'message')
  218. this.logger.error({ foo: 'bar' }, 'message')
  219. this.logger.error({ foo: 'bar' }, 'message')
  220. this.logger.error({ foo: 'bar' }, 'message')
  221. // the following errors should not be reported
  222. this.logger.error({ foo: 'bar' }, 'message')
  223. this.logger.error({ foo: 'bar' }, 'message')
  224. this.logger.error({ foo: 'bar' }, 'message')
  225. this.logger.error({ foo: 'bar' }, 'message')
  226. // allow a minute to pass
  227. this.clock.tick(this.start + 61 * 1000)
  228. // after a minute the next five errors should be reported to sentry
  229. this.logger.error({ foo: 'bar' }, 'message')
  230. this.logger.error({ foo: 'bar' }, 'message')
  231. this.logger.error({ foo: 'bar' }, 'message')
  232. this.logger.error({ foo: 'bar' }, 'message')
  233. this.logger.error({ foo: 'bar' }, 'message')
  234. // the following errors should not be reported to sentry
  235. this.logger.error({ foo: 'bar' }, 'message')
  236. this.logger.error({ foo: 'bar' }, 'message')
  237. this.logger.error({ foo: 'bar' }, 'message')
  238. this.logger.error({ foo: 'bar' }, 'message')
  239. this.captureException.callCount.should.equal(10)
  240. })
  241. describe('reportedToSentry', function () {
  242. it('should mark the error as reported to sentry', function () {
  243. const err = new Error()
  244. this.logger.error({ err }, 'message')
  245. expect(this.captureException.called).to.equal(true)
  246. expect(err.reportedToSentry).to.equal(true)
  247. })
  248. it('should mark two errors as reported to sentry', function () {
  249. const err1 = new Error()
  250. const err2 = new Error()
  251. this.logger.error({ err: err1, err2 }, 'message')
  252. expect(this.captureException.called).to.equal(true)
  253. expect(err1.reportedToSentry).to.equal(true)
  254. expect(err2.reportedToSentry).to.equal(true)
  255. })
  256. it('should not mark arbitrary objects as reported to sentry', function () {
  257. const err = new Error()
  258. const ctx = { foo: 'bar' }
  259. this.logger.error({ err, ctx }, 'message')
  260. expect(this.captureException.called).to.equal(true)
  261. expect(ctx.reportedToSentry).to.equal(undefined)
  262. })
  263. })
  264. })
  265. describe('checkLogLevelFile', function () {
  266. it('should request log level override from the config map', async function () {
  267. this.logger.getTracingEndTime = this.logger.getTracingEndTimeFile
  268. await this.logger.checkLogLevel()
  269. this.Fs.promises.readFile.should.have.been.calledWithMatch(
  270. '/logging/tracingEndTime'
  271. )
  272. })
  273. describe('when read errors', function () {
  274. beforeEach(async function () {
  275. this.Fs.promises.readFile.throws(new Error('test read error'))
  276. this.logger.getTracingEndTime = this.logger.getTracingEndTimeFile
  277. await this.logger.checkLogLevel()
  278. })
  279. it('should only set default level', function () {
  280. this.bunyanLogger.level.should.have.been.calledOnce.and.calledWith(
  281. 'debug'
  282. )
  283. })
  284. })
  285. describe('when the file is empty', function () {
  286. beforeEach(async function () {
  287. this.Fs.promises.readFile.returns('')
  288. this.logger.getTracingEndTime = this.logger.getTracingEndTimeFile
  289. await this.logger.checkLogLevel()
  290. })
  291. it('should only set default level', function () {
  292. this.bunyanLogger.level.should.have.been.calledOnce.and.calledWith(
  293. 'debug'
  294. )
  295. })
  296. })
  297. describe('when time value returned that is less than current time', function () {
  298. beforeEach(async function () {
  299. this.Fs.promises.readFile.returns('1')
  300. this.logger.getTracingEndTime = this.logger.getTracingEndTimeFile
  301. await this.logger.checkLogLevel()
  302. })
  303. it('should only set default level', function () {
  304. this.bunyanLogger.level.should.have.been.calledOnce.and.calledWith(
  305. 'debug'
  306. )
  307. })
  308. })
  309. describe('when time value returned that is more than current time', function () {
  310. describe('when level is already set', function () {
  311. beforeEach(async function () {
  312. this.bunyanLogger.level.returns(10)
  313. this.Fs.promises.readFile.returns((this.start + 1000).toString())
  314. this.logger.getTracingEndTime = this.logger.getTracingEndTimeFile
  315. await this.logger.checkLogLevel()
  316. })
  317. it('should set trace level', function () {
  318. this.bunyanLogger.level.should.have.been.calledOnce.and.calledWith(
  319. 'trace'
  320. )
  321. })
  322. })
  323. describe('when level is not already set', function () {
  324. beforeEach(async function () {
  325. this.bunyanLogger.level.returns(20)
  326. this.Fs.promises.readFile.returns((this.start + 1000).toString())
  327. this.logger.getTracingEndTime = this.logger.getTracingEndTimeFile
  328. await this.logger.checkLogLevel()
  329. })
  330. it('should set trace level', function () {
  331. this.bunyanLogger.level.should.have.been.calledOnce.and.calledWith(
  332. 'trace'
  333. )
  334. })
  335. })
  336. })
  337. })
  338. describe('checkLogLevelMetadata', function () {
  339. beforeEach(function () {
  340. this.logger = this.LoggingManager.initialize(this.loggerName)
  341. })
  342. describe('checkLogLevel', function () {
  343. it('should request log level override from google meta data service', async function () {
  344. this.logger.getTracingEndTime = this.logger.getTracingEndTimeMetadata
  345. await this.logger.checkLogLevel()
  346. const options = {
  347. headers: {
  348. 'Metadata-Flavor': 'Google'
  349. }
  350. }
  351. const uri = `http://metadata.google.internal/computeMetadata/v1/project/attributes/${this.loggerName}-setLogLevelEndTime`
  352. this.Fetch.should.have.been.calledWithMatch(uri, options)
  353. })
  354. describe('when request has error', function () {
  355. beforeEach(async function () {
  356. this.Fetch = sinon.stub().throws()
  357. this.logger.getTracingEndTime = this.logger.getTracingEndTimeMetadata
  358. await this.logger.checkLogLevel()
  359. })
  360. it('should only set default level', function () {
  361. this.bunyanLogger.level.should.have.been.calledOnce.and.calledWith(
  362. 'debug'
  363. )
  364. })
  365. })
  366. describe('when statusCode is not 200', function () {
  367. beforeEach(async function () {
  368. this.fetchResponse.status = 404
  369. this.logger.getTracingEndTime = this.logger.getTracingEndTimeMetadata
  370. await this.logger.checkLogLevel()
  371. })
  372. it('should only set default level', function () {
  373. this.bunyanLogger.level.should.have.been.calledOnce.and.calledWith(
  374. 'debug'
  375. )
  376. })
  377. })
  378. describe('when time value returned that is less than current time', function () {
  379. beforeEach(async function () {
  380. this.logger.getTracingEndTime = this.logger.getTracingEndTimeMetadata
  381. this.fetchResponse.text = sinon.stub().resolves('1')
  382. await this.logger.checkLogLevel()
  383. })
  384. it('should only set default level', function () {
  385. this.bunyanLogger.level.should.have.been.calledOnce.and.calledWith(
  386. 'debug'
  387. )
  388. })
  389. })
  390. describe('when time value returned that is more than current time', function () {
  391. describe('when level is already set', function () {
  392. beforeEach(async function () {
  393. this.bunyanLogger.level.returns(10)
  394. this.fetchResponse.text = sinon
  395. .stub()
  396. .resolves((this.start + 1000).toString())
  397. this.logger.getTracingEndTime =
  398. this.logger.getTracingEndTimeMetadata
  399. await this.logger.checkLogLevel()
  400. })
  401. it('should set trace level', function () {
  402. this.bunyanLogger.level.should.have.been.calledOnce.and.calledWith(
  403. 'trace'
  404. )
  405. })
  406. })
  407. describe('when level is not already set', function () {
  408. beforeEach(async function () {
  409. this.bunyanLogger.level.returns(20)
  410. this.fetchResponse.text = sinon
  411. .stub()
  412. .resolves((this.start + 1000).toString())
  413. this.Fetch.fetch = sinon.stub().resolves(this.fetchResponse)
  414. this.logger.getTracingEndTime =
  415. this.logger.getTracingEndTimeMetadata
  416. await this.logger.checkLogLevel()
  417. })
  418. it('should set trace level', function () {
  419. this.bunyanLogger.level.should.have.been.calledOnce.and.calledWith(
  420. 'trace'
  421. )
  422. })
  423. })
  424. })
  425. })
  426. })
  427. describe('ringbuffer', function () {
  428. beforeEach(function () {
  429. this.logBufferMock = [
  430. { msg: 'log 1' },
  431. { msg: 'log 2' },
  432. { level: 50, msg: 'error' }
  433. ]
  434. })
  435. describe('when ring buffer size is positive', function () {
  436. beforeEach(function () {
  437. process.env.LOG_RING_BUFFER_SIZE = '20'
  438. this.logger = this.LoggingManager.initialize(this.loggerName)
  439. this.logger.ringBuffer.records = this.logBufferMock
  440. this.logger.error({}, 'error')
  441. })
  442. afterEach(function () {
  443. process.env.LOG_RING_BUFFER_SIZE = undefined
  444. })
  445. it('should include buffered logs in error log and filter out error logs in buffer', function () {
  446. this.bunyanLogger.error.lastCall.args[0].logBuffer.should.deep.equal([
  447. { msg: 'log 1' },
  448. { msg: 'log 2' }
  449. ])
  450. })
  451. })
  452. describe('when ring buffer size is zero', function () {
  453. beforeEach(function () {
  454. process.env.LOG_RING_BUFFER_SIZE = '0'
  455. this.logger = this.LoggingManager.initialize(this.loggerName)
  456. this.logger.error({}, 'error')
  457. })
  458. afterEach(function () {
  459. process.env.LOG_RING_BUFFER_SIZE = undefined
  460. })
  461. it('should not include buffered logs in error log', function () {
  462. expect(this.bunyanLogger.error.lastCall.args[0].logBuffer).be.undefined
  463. })
  464. })
  465. })
  466. describe('stackdriver logging', function () {
  467. describe('when STACKDRIVER_LOGGING is unset', function () {
  468. beforeEach(function () {
  469. process.env.STACKDRIVER_LOGGING = undefined
  470. this.LoggingManager.initialize(this.loggerName)
  471. })
  472. it('is disabled', function () {
  473. expect(this.bunyanLogger.addStream).not.to.have.been.calledWith(
  474. this.stackdriverStreamConfig
  475. )
  476. })
  477. })
  478. describe('when STACKDRIVER_LOGGING is true', function () {
  479. beforeEach(function () {
  480. process.env.STACKDRIVER_LOGGING = 'true'
  481. this.LoggingManager.initialize(this.loggerName)
  482. })
  483. it('is enabled', function () {
  484. expect(this.bunyanLogger.addStream).to.have.been.calledWith(
  485. this.stackdriverStreamConfig
  486. )
  487. })
  488. it('is configured properly', function () {
  489. expect(this.GCPLogging.LoggingBunyan).to.have.been.calledWith({
  490. logName: this.loggerName,
  491. serviceContext: { service: this.loggerName }
  492. })
  493. })
  494. })
  495. })
  496. })