loggingManagerTests.js 19 KB

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