loggingManagerTests.js 19 KB

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