Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

winston-elasticsearch

vanthome294.7kMIT0.19.0TypeScript support: included

An Elasticsearch transport for winston

logging, winston, elasticsearch, transport, logstash

readme

winston-elasticsearch

Version npm Build Status Dependencies Coverage Status

An elasticsearch transport for the winston logging toolkit.

Features

  • logstash compatible message structure.
  • Thus consumable with kibana.
  • Date pattern based index names.
  • Custom transformer function to transform logged data into a different message structure.
  • Buffering of messages in case of unavailability of ES. The limit is the memory as all unwritten messages are kept in memory.

Compatibility

For Winston 3.7, Elasticsearch 8.0 and later, use the >= 0.17.0. For Winston 3.4, Elasticsearch 7.8 and later, use the >= 0.16.0. For Winston 3.x, Elasticsearch 7.0 and later, use the >= 0.7.0. For Elasticsearch 6.0 and later, use the 0.6.0. For Elasticsearch 5.0 and later, use the 0.5.9. For earlier versions, use the 0.4.x series.

Unsupported / Todo

  • Querying.

Installation

npm install --save winston winston-elasticsearch

Usage

const winston = require('winston');
const { ElasticsearchTransport } = require('winston-elasticsearch');

const esTransportOpts = {
  level: 'info'
};
const esTransport = new ElasticsearchTransport(esTransportOpts);
const logger = winston.createLogger({
  transports: [
    esTransport
  ]
});
// Compulsory error handling
logger.on('error', (error) => {
  console.error('Error in logger caught', error);
});
esTransport.on('error', (error) => {
  console.error('Error in logger caught', error);
});

The winston API for logging can be used with one restriction: Only one JS object can only be logged and indexed as such. If multiple objects are provided as arguments, the contents are stringified.

Options

  • level [info] Messages logged with a severity greater or equal to the given one are logged to ES; others are discarded.
  • index [none | when dataStream is true, logs-app-default] The index to be used. This option is mutually exclusive with indexPrefix.
  • indexPrefix [logs] The prefix to use to generate the index name according to the pattern <indexPrefix>-<indexSuffixPattern>. Can be string or function, returning the string to use.
  • indexSuffixPattern [YYYY.MM.DD] a Day.js compatible date/ time pattern.
  • transformer [see below] A transformer function to transform logged data into a different message structure.
  • useTransformer [true] If set to true, the given transformer will be used (or the default). Set to false if you want to apply custom transformers during Winston's createLogger.
  • ensureIndexTemplate [true] If set to true, the given indexTemplate is checked/ uploaded to ES when the module is sending the first log message to make sure the log messages are mapped in a sensible manner.
  • indexTemplate [see file index-template-mapping.json] the mapping template to be ensured as parsed JSON. ensureIndexTemplate is true and indexTemplate is undefined
  • flushInterval [2000] Time span between bulk writes in ms.
  • retryLimit [400] Number of retries to connect to ES before giving up.
  • healthCheckTimeout [30s] Timeout for one health check (health checks will be retried forever).
  • healthCheckWaitForStatus [yellow] Status to wait for when check upon health. See its API docs for supported options.
  • healthCheckWaitForNodes [>=1] Nodes to wait for when check upon health. See its API docs for supported options.
  • client An elasticsearch client instance. If given, the clientOpts are ignored.
  • clientOpts An object passed to the ES client. See its docs for supported options.
  • waitForActiveShards [1] Sets the number of shard copies that must be active before proceeding with the bulk operation.
  • pipeline [none] Sets the pipeline id to pre-process incoming documents with. See the bulk API docs.
  • buffering [true] Boolean flag to enable or disable messages buffering. The bufferLimit option is ignored if set to false.
  • bufferLimit [null] Limit for the number of log messages in the buffer.
  • apm [null] Inject apm client to link elastic logs with elastic apm traces.
  • dataStream [false] Use Elasticsearch datastreams.
  • source [none] the source of the log message. This can be useful for microservices to understand from which service a log message origins.
  • internalLogger [console.error] A logger of last resort to log internal errors.

Logging of ES Client

The default client and options will log through console.

Interdependencies of Options

When changing the indexPrefix and/or the transformer, make sure to provide a matching indexTemplate.

Transformer

The transformer function allows mutation of log data as provided by winston into a shape more appropriate for indexing in Elasticsearch.

The default transformer generates a @timestamp and rolls any meta objects into an object called fields.

Params:

  • logdata An object with the data to log. Properties are:
    • timestamp [new Date().toISOString()] The timestamp of the log entry
    • level The log level of the entry
    • message The message for the log entry
    • meta The meta data for the log entry

Returns: Object with the following properties

  • @timestamp The timestamp of the log entry
  • severity The log level of the entry
  • message The message for the log entry
  • fields The meta data for the log entry

The default transformer function's transformation is shown below.

Input A:

{
  "message": "Some message",
  "level": "info",
  "meta": {
    "method": "GET",
    "url": "/sitemap.xml",
    ...
  }
}

Output A:

{
  "@timestamp": "2019-09-30T05:09:08.282Z",
  "message": "Some message",
  "severity": "info",
  "fields": {
    "method": "GET",
    "url": "/sitemap.xml",
    ...
  }
}

The default transformer can be imported and extended

Example

  const { ElasticsearchTransformer } = require('winston-elasticsearch');
  const esTransportOpts = {
  transformer: (logData) => {
   const transformed = ElasticsearchTransformer(logData);
   transformed.fields.customField = 'customValue'
   return transformed;
 }};
const esTransport = new ElasticsearchTransport(esTransportOpts);

Note that in current logstash versions, the only "standard fields" are @timestamp and @version, anything else is just free.

A custom transformer function can be provided in the options initiation.

Events

  • error: in case of any error.

Example

An example assuming default settings.

Log Action

logger.info('Some message', {});

Only JSON objects are logged from the meta field. Any non-object is ignored.

Generated Message

The log message generated by this module has the following structure:

{
  "@timestamp": "2019-09-30T05:09:08.282Z",
  "message": "Some log message",
  "severity": "info",
  "fields": {
    "method": "GET",
    "url": "/sitemap.xml",
    "headers": {
      "host": "www.example.com",
      "user-agent": "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
      "accept": "*/*",
      "accept-encoding": "gzip,deflate",
      "from": "googlebot(at)googlebot.com",
      "if-modified-since": "Tue, 30 Sep 2019 11:34:56 GMT",
      "x-forwarded-for": "66.249.78.19"
    }
  }
}

Target Index

This message would be POSTed to the following endpoint:

http://localhost:9200/logs-2019.09.30/log/

So the default mapping uses an index pattern logs-*.

Logs correlation with Elastic APM

Instrument your code

yarn add elastic-apm-node
- or -
npm install elastic-apm-node

Then, before any other require in your code, do:

const apm = require("elastic-apm-node").start({
  serverUrl: "<apm server http url>"
})

// Set up the logger
var winston = require('winston');
var Elasticsearch = require('winston-elasticsearch');

var esTransportOpts = {
  apm,
  level: 'info',
  clientOpts: { node: "<elastic server>" }
};
var logger = winston.createLogger({
  transports: [
    new Elasticsearch(esTransportOpts)
  ]
});

Inject apm traces into logs

logger.info('Some log message');

Will produce:

{
  "@timestamp": "2021-03-13T20:35:28.129Z",
  "message": "Some log message",
  "severity": "info",
  "fields": {},
  "transaction": {
    "id": "1f6c801ffc3ae6c6"
  },
  "trace": {
    "id": "1f6c801ffc3ae6c6"
  }
}

Notice

Some "custom" logs may not have the apm trace.

If that is the case, you can retrieve traces using apm.currentTraceIds like so:

logger.info("Some log message", { ...apm.currentTracesIds })

The transformer function (see above) will place the apm trace in the root object so that kibana can link Logs to APMs.

Custom traces WILL TAKE PRECEDENCE

If you are using a custom transformer, you should add the following code into it:

  if (logData.meta['transaction.id']) transformed.transaction = { id: logData.meta['transaction.id'] };
  if (logData.meta['trace.id']) transformed.trace = { id: logData.meta['trace.id'] };
  if (logData.meta['span.id']) transformed.span = { id: logData.meta['span.id'] };

This scenario may happen on a server (e.g. restify) where you want to log the query after it was sent to the client (e.g. using server.on('after', (req, res, route, error) => log.debug("after", { route, error }))). In that case you will not get the traces into the response because traces would have stopped (as the server sent the response to the client).

In that scenario, you could do something like so:

server.use((req, res, next) => {
  req.apm = apm.currentTracesIds
  next()
})
server.on("after", (req, res, route, error) => log.debug("after", { route, error, ...req.apm }))

Manual Flushing

Flushing can be manually triggered like this:

const esTransport = new ElasticsearchTransport(esTransportOpts);
esTransport.flush();

Datastreams

Elasticsearch 7.9 and higher supports Datastreams.

When dataStream: true is set, bulk indexing happens with create instead of index, and also the default naming convention is logs-*-*, which will match the built-in Index template and ILM policy, automatically creating a datastream.

By default, the datastream will be named logs-app-default, but alternatively, you can set the index option to anything that matches logs-*-* to make use of the built-in template and ILM policy.

If dataStream: true is enabled, AND ( you are using Elasticsearch < 7.9 OR (you have set a custom index that does not match logs-*-* AND you have not created a custom matching template in Elasticsearch)), a normal index will be created.

changelog

0.19.0 / 2024-05-11

  • Upgrade dependencies

0.18.0 / 2024-03-04

  • Upgrade dependencies

0.17.3 / 2023-09-01

  • Upgrade dependencies

0.17.2 / 2023-02-16

  • Fix typings

0.17.1 / 2022-05-15

  • Fix typings

0.17.0 / 2022-05-15

  • Upgrade dependencies, major new ES client version

0.16.1 / 2022-01-24

  • Upgrade dependencies
  • Expose option internalLogger for last resort logger

0.16.0 / 2021-12-08

  • Add more debug output
  • Upgrade dependencies
  • Fix duplicate entries when buffering is used

0.15.9 / 2021-09-14

  • Fix last resort error logging

0.15.8 / 2021-07-25

  • Fix last resort error logging

0.15.7 / 2021-06-25

  • Upgrade optional APM dependency for making it work with node 16.

0.15.6 / 2021-06-02

  • Upgrade ES client.

0.15.5 / 2021-05-25

  • Expose transformer function so that it can be adapted.

0.15.4 / 2021-04-09

  • Upgrade ES client
  • Add console.log output in case of bulk writer errors

0.15.3 / 2021-03-20

  • Fix indexPrefix can be of type string | Function
  • Fix travis build process (ES JS Client (7.11.2 instead of 11), nodejs 8 deprecated on yargs)
  • Fix templateName is undefined or null if options.index is undefined or null
  • Correct npm link in README.md (browsenpm.org isn't connected to npm anymore)
  • Prevents resending successfully sent items.
  • Add retryLimit option
  • Fix index name not being passed to bulk writer

0.15.1 / 2021-03-02

  • Fix index name not being passed to bulk writer

0.15.0 / 2021-02-28

  • Introduce source parameter
  • Fix some datastream issues
  • Remove _type and don't write it

0.14.0 / 2021-02-24

  • Rename config Property ensureMappingTemplate to ensureIndexTemplate and mappingTemplate accordingly
  • Make Index Templates not appear as Legacy ones in Kibana, use putIndexTemplate instead of putTemplate

0.13.0 / 2021-02-12

  • ES 11 JS Client
  • Support for data streams
  • Drop support for ES <= 6

0.12.3 / 2020-12-04

  • Increase retries from 5 to 400 (almost 7 minutes) as some massive uServices systems take a while until they spun up

0.12.2 / 2020-11-26

  • Inject indexing error in case writing to ES fails

0.12.1 / 2020-11-13

  • Use latest ES client
  • Docs fixes

0.12.0 / 2020-11-02

  • Make retry mechanism give up after 5 retries
  • Make emit a warning only when the max retry has been reached
  • Make APM param optional
  • Move APM dependency into normal dependencies

0.11.0 / 2020-10-22

  • Improve typings
  • Added flush() method to ES transport

0.10.0 / 2020-08-18

  • Emit transport internal errors no longer as error but as warning because even when listened to with .on('error', ...) it lead to an UnhandledPromiseRejectionWarning.

0.9.0 / 2020-05-16

  • Upgrade ES Client
  • New approach to error handling where, in case of an emitted error the source stream is automatically re-attached to the transport stream
  • This commit adds a retry counter - after the number of retries has been exceeded then the document is discarded.
  • Exposes healthcheck options
  • ES version specific mapping templates

0.8.8 / 2020-04-07

  • Fix typings

0.8.7 / 2020-04-02

  • Fix typings

0.8.6 / 2020-04-01

  • Remove default export from typings

0.8.5 / 2020-03-09

  • Upgrade dependencies
  • Correct order for entries with same timestamp
  • Fix edge case with this.client.bulk

0.8.4 / 2020-01-20

  • Upgrade typings
  • Make compatible with ES client 7.6

0.8.3 / 2019-01-20

  • Upgrade deps
  • Make compatible with ES client 7.5
  • Add -* to given index pattern prefix for creating index pattern

0.8.2 / 2019-11-01

  • Upgrade deps
  • Use existsTemplate instead of getTemplate
  • Make buffering in case of outages more stable
  • Don't provide type anymore with ES client's bulk operation
  • Default to all for waitForActiveShards
  • Emit more error events in error cases
  • Adapt default index template to conform with newer ES version

0.8.1 / 2019-10-01

  • Update typings

0.8.0 / 2019-09-01

  • Switch to new official ES client
  • Emit error events when an error happens

0.7.13 / 2019-08-28

  • Upgrade to ES client
  • Remove unneeded dependency
  • Reduce package size by swapping moment for days.js and other measured

0.7.12 / 2019-05-15

0.7.11 / 2019-04-23

  • Prevent .git from being published to npm

0.7.10 / 2019-04-17

  • Properly implement non buffering case --> immediately write any message to ES
  • Upgrade deps and several other cleanups
  • Upgrade of typings
  • Correct documentation that we use _doc as default type`

0.7.9 / 2019-02-12

  • Upgrade deps, also Winston 3.2.1
  • Incorporate fix to prevent flush called twice after each interval instead of once
  • Better ignore extraneous resources pushed to npm

0.7.8 / 2019-01-27

  • Upgrade deps, also Winston 3.2.0
  • Update the documentation

0.7.7 / 2018-12-28

  • Add feature to limit message buffering

0.7.6 / 2018-12-28

  • Upgrade deps
  • Allow the process to exit when the logger is ended.

0.7.5 / 2018-09-30

  • Upgrade to Winston 3.1.0
  • Documentation fixes

0.7.4 / 2018-07-23

  • Make sure no messages are lost in case of an ES level fault
  • Add a Typescript declaration file
  • Fix bug in ES fault handler

0.7.3 / 2018-06-30

  • Possibility to have an indexInterfix

0.7.2 / 2018-06-30

  • Remove _all field from default mapping as it is deprecated in ES
  • Support logger.info({ message: 'Test', foo: 'bar' }); signature as well (make sure that field foo ends up in fields in the index)

0.7.1 / 2018-06-18

0.7.0 / 2018-06-17

  • Upgrade to winston 3.0 and elasticsearch 15.0
  • Actually use message type _doc as default
  • Mapping template changed --> if you have a custom mapping please check!

0.6.0 / 2018-04-28

0.5.9 / 2018-04-16

  • Fix bug that lead to mapping template not being used
  • Upgrade deps

0.5.8 / 2018-03-28

Better error handling.

0.5.7 / 2018-02-14

  • In order to prevent UnhandledPromiseRejectionWarning and tackle node.js deprecation DEP0018, catching and logging to console is now the default way of handling internal errors
  • Enable sniffOnConnectionFault on ES client by default
  • Change default mapping: template --> index_patterns
  • Migrate default mapping according to https://www.elastic.co/blog/strings-are-dead-long-live-strings
  • Moved retry logic into bulkwriter to handle intermittent connectivity interruptions gracefully AND be able to resume operation
  • Connection testing is now running infinitely which means the logger never gives up
  • Messages logged during a connection outage are buffered

0.5.6 / 2017-12-24

  • Rename debug key from bulk writer to winston:elasticsearch
  • use finally() instead of then() to schedule bulk writes even in case of exceptions

0.5.5 / 2017-12-15

  • Fix issue with loading built-in mapping
  • Upgrade to Elasticsearch client 14 (Elasticsearch 6)
  • Ignore 404 errors for silent creation of new indexes

0.5.3 / 2017-10-02

  • Upgrade to Winston 2.4.0

0.5.2 / 2017-09-28

  • Add pipeline option for elasticsearch

0.5.1 / 2017-09-24

  • Upgrade all deps
  • Fix linting issues
  • Fix loading of template file previously done with require()

0.5.0 / 2016-12-01

  • Release for Elasticsearch 5
  • Remove consistency option
  • Introduce waitForActiveShards option

0.4.2 / 2016-11-12

  • Allow consistency to be disabled using false as value
  • Upgrade deps

0.4.1 / 2016-10-26

  • Add timestamp automatically to log messages

0.4.0 / 2016-05-31

  • Minimum node.js version 6
  • Version upgrades
  • Migrate to eslint from jshint and jscs

0.3.1 / 2016-04-22

  • Fix for dependencies - move winstom from devDependencies to dependencies in package.json

0.3.0 / 2016-03-30

  • Test with ES 2.3.1
  • Add time driven bulk write functionality.
  • Remove retry functionality for writes as now covered by bulk writer.
  • Tests for ES unavailable case.

0.2.6 / 2016-01-19

  • Fix for Windows platform -- make default mapping file readable.

0.2.5 / 2015-12-01

  • ES 2.1 support (driver update).

0.2.4 / 2015-11-08

  • Support ES 2.0, really.
  • Support for single index usage, without data suffix via index option.
  • Fix bug when ES client is provided.

0.2.3 / 2015-11-01

  • Support ES 2.0.

0.2.2 / 2015-09-23

  • Add jshint jscs.
  • Minor cleanups.

0.2.1 / 2015-09-10

  • Add transport name.
  • Call super constructor for inheritance.

0.2.0 / 2015-09-03

  • 90% rewrite.
  • Use current dependencies.
  • Removed feature to generate process stats automatically.
  • Removed functionality to generate other implicit fields like @tags.
  • Add transformer functionality to modify structure of messages before logging.
  • Introduce connection state checking and basic retry mechanism for main ES operations.