loggingManagerTests.js 19 KB

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