Skip to content

Instantly share code, notes, and snippets.

@trasa
Created February 23, 2019 19:47
Show Gist options
  • Save trasa/1efaee47267db3de079024ec99a1c823 to your computer and use it in GitHub Desktop.
Save trasa/1efaee47267db3de079024ec99a1c823 to your computer and use it in GitHub Desktop.
A Winston Transport for Elasticsearch that doesn't have any queueing of messages to ES.
const winston = require('winston'),
_ = require('lodash'),
moment = require('moment'),
Transport = require('winston-transport'),
elasticsearch = require('elasticsearch');
module.exports = class SimpleElasticsearch extends Transport {
constructor(opts) {
super(opts);
this.name = 'simple_elasticsearch';
this.opts = opts || {};
// defaults
_.defaults(opts, {
level: 'info',
index: null,
indexPrefix: 'logs',
indexSuffixPattern: 'YYYY.MM.DD',
messageType: '_doc'
});
if (opts.client) {
this.client = opts.client;
} else {
_.defaults(opts, {
clientOpts: {
log: [
{
type: 'console',
level: 'error',
}
]
}
});
this.client = new elasticsearch.Client(_.clone(this.opts.clientOpts));
}
}
log(info, callback) {
const {level, message} = info;
this.client.index({
index: this.getIndexName(this.opts),
type: this.opts.messageType,
body: {
'@timestamp': new Date().toISOString(),
message: message,
severity: level,
fields: {}
}
}, () => {
if (callback) {
callback();
}
});
}
// taken from winston-elasticsearch
getIndexName(opts, indexInterfix) {
this.test = 'test';
let indexName = opts.index;
if (indexName === null) {
// eslint-disable-next-line prefer-destructuring
let indexPrefix = opts.indexPrefix;
if (typeof indexPrefix === 'function') {
// eslint-disable-next-line prefer-destructuring
indexPrefix = opts.indexPrefix();
}
const now = moment();
const dateString = now.format(opts.indexSuffixPattern);
indexName = indexPrefix + (indexInterfix !== undefined ? '-' + indexInterfix : '') + '-' + dateString;
}
return indexName;
}
};
winston.transports.SimpleElasticsearch = module.exports;
@jssblck
Copy link

jssblck commented Oct 25, 2019

Awesome. Thanks so much for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment