loggingManagerTests.js 18 KB

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