loggingManagerTests.js 19 KB

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