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