loggingManagerTests.js 19 KB

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