loggingManagerTests.js 19 KB

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