loggingManagerTests.js 20 KB

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