Winston Elasticsearch Transport Indexing

Ship Winston logs to Elasticsearch with bulk indexing, retry on rejection, and index rotation mapping that keeps queries fast over time.

TypescriptNodeResilience

Code

typescriptsnippet
31 lines
import winston from 'winston';
import 'winston-elasticsearch';

const esTransport = new winston.transports.Elasticsearch({
  index: 'svc-logs',
  indexPrefixTemplate: 'svc-logs',
  clientOpts: { node: 'http://elastic:9200' },
  buffering: true,
  bufferLimit: 500,
  flushInterval: 5_000,
  ensureIndexTemplate: true,
  retryLimit: 3,
});

export const logger = winston.createLogger({
  level: 'info',
  defaultMeta: { service: 'search-api', env: process.env.NODE_ENV },
  format: winston.format.combine(
    winston.format.timestamp({ format: 'YYYY-MM-DDTHH:mm:ss.SSSZ' }),
    winston.format.json(),
  ),
  transports: [esTransport],
});

logger.info('query served', { query: 'blue shoes', tookMs: 18, hits: 231 });
logger.warn('slow query', { query: 'umbrella', tookMs: 950 });
logger.error('upstream timeout', { shard: 's-3', retry: 1 });

esTransport.on('error', (err) => {
  process.stderr.write('es transport failed: ' + err.message + '\n');
});

How the file gets its result

Top-level bindings esTransport hold the demo state — nothing sits inside a function scope.

Configuration comes from the environment — it reads NODE_ENV, so the same code switches behavior between environments without edits.

Emits through the .info, .warn, .error level methods with structured payloads, so downstream transports can route by level and field.

Points of care

  • External dependency: winston — install it before running the snippet.

Putting it to use

The primary signature is export const logger =

logger is what another module would consume; nothing else here is load-bearing for callers.

Core lines

esTransport.on('error', (err) => {
  process.stderr.write('es transport failed: ' + err.message + '\n');
});

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
`winston` — install it with the package manager before running.