diff --git a/src/lib/formatHEC.js b/src/lib/formatHEC.js new file mode 100644 index 0000000..4d6a5a0 --- /dev/null +++ b/src/lib/formatHEC.js @@ -0,0 +1,5 @@ +const formatHEC = ({ level, message, meta = {} } = {}) => { + return message ? Object.assign({}, { level, message }, meta) : Object.assign({}, { level }, meta); +}; + +export default formatHEC; diff --git a/src/lib/transports/splunkHEC.js b/src/lib/transports/splunkHEC.js index 39c237e..2b437a3 100644 --- a/src/lib/transports/splunkHEC.js +++ b/src/lib/transports/splunkHEC.js @@ -1,10 +1,12 @@ import winston from 'winston'; +import formatHEC from '../formatHEC'; const https = require('https'); class SplunkHEC extends winston.Transport { log (level, message, meta) { const httpsAgent = new https.Agent({ keepAlive: true }); + const formattedMessage = formatHEC({ level, message, meta }); const data = { 'time': Date.now(), @@ -12,7 +14,7 @@ class SplunkHEC extends winston.Transport { 'source': `/var/log/apps/heroku/ft-${process.env.SYSTEM_CODE}.log`, 'sourcetype': '_json', 'index': 'heroku', - 'event': { level, message, meta } + 'event': formattedMessage }; return fetch('https://http-inputs-financialtimes.splunkcloud.com/services/collector/event', { diff --git a/test/lib/formatHEC.test.js b/test/lib/formatHEC.test.js new file mode 100644 index 0000000..41c8da4 --- /dev/null +++ b/test/lib/formatHEC.test.js @@ -0,0 +1,66 @@ +const chai = require('chai'); +chai.should(); +const expect = chai.expect; + +import formatHEC from '../../dist/lib/formatHEC'; + +describe('FormatHEC', () => { + + it('should exist', () => { + formatHEC.should.exist; + }); + + it('should format all data options', () => { + const options = { + level: 'info', + message: 'Hello world', + meta: { event: 'TEST' } + } + + expect(formatHEC(options)).to.deep.equal({ + level: 'info', + message: 'Hello world', + event: 'TEST' + }); + }); + + it('should handle data containing an error', () => { + const err = new Error('This is an error'); + const options = { + level: 'error', + meta: { event: 'TEST_ERROR', err } + } + + expect(formatHEC(options)).to.deep.equal({ + level: 'error', + event: 'TEST_ERROR', err + }); + }); + + it('should handle no meta data ', () => { + const options = { + level: 'info', + message: 'a message' + } + + expect(formatHEC(options)).to.deep.equal({ + level: 'info', + message: 'a message' + }); + }); + + it('should handle no message', () => { + const count = 10; + const options = { + level: 'info', + meta: { event: 'TEST', count } + } + + expect(formatHEC(options)).to.deep.equal({ + level: 'info', + event: 'TEST', + count: 10 + }); + }); + +});