Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
W

winston

> 编程语言
Open source

A logger for just about everything.

24.5K stars0 likes1 views
WebsiteGitHub

About

A logger for just about everything.

winston

A logger for just about everything.

winston@3

See the Upgrade Guide for more information. Bug reports and PRs welcome!

Looking for [email protected] documentation?

Please note that the documentation below is for winston@3. [Read the [email protected] documentation].

Motivation

winston is designed to be a simple and universal logging library with support for multiple transports. A transport is essentially a storage device for your logs. Each winston logger can have multiple transports (see: [Transports]) configured at different levels (see: [Logging levels]). For example, one may want error logs to be stored in a persistent remote location (like a database), but all logs output to the console or a local file.

winston aims to decouple parts of the logging process to make it more flexible and extensible. Attention is given to supporting flexibility in log formatting (see: [Formats]) & levels (see: [Using custom logging levels]), and ensuring those APIs decoupled from the implementation of transport logging (i.e. how the logs are stored / indexed, see: [Adding Custom Transports]) to the API that they exposed to the programmer.

Quick Start

TL;DR? Check out the [quick start example][quick-example] in ./examples/. There are a number of other examples in [./examples/*.js][examples]. Don't see an example you think should be there? Submit a pull request to add it!

Usage

The recommended way to use winston is to create your own logger. The simplest way to do this is using winston.createLogger:

…

You may also log directly via the default logger exposed by require('winston'), but this merely intended to be a convenient shared logger to use throughout your application if you so choose. Note that the default logger doesn't have any transports by default. You need add transports by yourself, and leaving the default logger without any transports may produce a high memory usage issue.

Table of contents

  • Motivation
  • Quick Start
  • Usage
  • Table of Contents
  • Logging
    • Creating your logger
    • Streams, objectMode, and info objects
  • [Formats]
    • Combining formats
    • String interpolation
    • Filtering info Objects
    • Creating custom formats
  • [Logging levels]
    • Using logging levels
    • Using custom logging levels
  • [Transports]
    • Multiple transports of the same type
    • Adding Custom Transports
    • Common Transport options
  • Exceptions
    • Handling Uncaught Exceptions with winston
    • To Exit or Not to Exit
  • Rejections
    • Handling Uncaught Promise Rejections with winston
  • Profiling
  • Streaming Logs
  • Querying Logs
  • Further Reading
    • Using the default logger
    • Awaiting logs to be written in winston
    • Working with multiple Loggers in winston
    • Routing Console transport messages to the console instead of stdout and stderr
  • Installation
  • Run Tests

Logging

Logging levels in winston conform to the severity ordering specified by [RFC5424]: severity of all levels is assumed to be numerically ascending from most important to least important.

javascript
const levels = {
  error: 0,
  warn: 1,
  info: 2,
  http: 3,
  verbose: 4,
  debug: 5,
  silly: 6
};

Creating your own Logger

You get started by creating a logger using winston.createLogger:

javascript
const logger = winston.createLogger({
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

A logger accepts the following parameters:

Name Default Description
level 'info' Log only if info.level is less than or equal to this level
levels winston.config.npm.levels Levels (and colors) representing log priorities
format winston.format.json Formatting for info messages (see: [Formats])
transports [] (No transports) Set of logging targets for info messages
exitOnError true If false, handled exceptions will not cause process.exit
silent false If true, all logs are suppressed

The levels provided to createLogger will be defined as convenience methods on the logger returned.

javascript
//
// Logging
//
logger.log({
  level: 'info',
  message: 'Hello distributed log files!'
});

logger.info('Hello again distributed logs');

You can add or remove transports from the logger once it has been provided to you from winston.createLogger:

javascript
const files = new winston.transports.File({ filename: 'combined.log' });
const console = new winston.transports.Console();

logger
  .clear()          // Remove all transports
  .add(console)     // Add console transport
  .add(files)       // Add file transport
  .remove(console); // Remove console transport

You can also wholesale reconfigure a winston.Logger instance using the configure method:

javascript
const logger = winston.createLogger({
  level: 'info',
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

//
// Replaces the previous transports with those in the
// new configuration wholesale.
//
const DailyRotateFile = require('winston-daily-rotate-file');
logger.configure({
  level: 'verbose',
  transports: [
    new DailyRotateFile(opts)
  ]
});

Creating child loggers

You can create child loggers from existing loggers to pass metadata overrides:

javascript
const logger = winston.createLogger({
  transports: [
    new winston.transports.Console(),
  ]
});

const childLogger = logger.child({ requestId: '451' });

.child is likely to be bugged if you're also extending the Logger class, due to some implementation details that make this keyword to point to unexpected things. Use with caution.

Streams, objectMode, and info objects

In winston, both Logger and Transport instances are treated as objectMode streams that accept an info object.

The info parameter provided to a given format represents a single log message. The object itself is mutable. Every info must have at least the level and message properties:

javascript
const info = {
  level: 'info',                 // Level of the logging message
  message: 'Hey! Log something?' // Descriptive message being logged.
};

Properties besides level and message are considered as "meta". i.e.:

javascript
const { level, message, ...meta } = info;

Several of the formats in logform itself add additional properties:

Property Format added by Description
splat splat() String interpolation splat for %d %s-style messages.
timestamp timestamp() timestamp the message was received.
label label() Custom label associated with each message.
ms ms() Number of milliseconds since the previous log message.

As a consumer you may add whatever properties you wish – internal state is maintained by Symbol properties:

  • Symbol.for('level') (READ-ONLY): equal to level property. Is treated as immutable by all code.
  • Symbol.for('message'): complete string message set by "finalizing formats":
    • json
    • logstash
    • printf
    • prettyPrint
    • simple
  • Symbol.for('splat'): additional string interpolation arguments. Used exclusively by splat() format.

These Symbols are stored in another package: triple-beam so that all consumers of logform can have the same Symbol reference. i.e.:

javascript
const { LEVEL, MESSAGE, SPLAT } = require('triple-beam');

console.log(LEVEL === Symbol.for('level'));
// true

console.log(MESSAGE === Symbol.for('message'));
// true

console.log(SPLAT === Symbol.for('splat'));
// true

NOTE: any { message } property in a meta object provided will automatically be concatenated to any msg already provided: For example the below will concatenate 'world' onto 'hello':

javascript
logger.log('error', 'hello', { message: 'world' });
logger.info('hello', { message: 'world' });

Formats

Formats in winston can be accessed from winston.format. They are implemented in logform, a separate module from winston. This allows flexibility when writing your own transports in case you wish to include a default format with your transport.

In modern versions of node template strings are very performant and are the recommended way for doing most end-user formatting. If you want to bespoke format your logs, winston.format.printf is for you:

javascript
const { createLogger, format, transports } = require('winston');
const { combine, timestamp, label, printf } = format;

const myFormat = printf(({ level, message, label, timestamp }) => {
  return `${timestamp} [${label}] ${level}: ${message}`;
});

const logger = createLogger({
  format: combine(
    label({ label: 'right meow!' }),
    timestamp(),
    myFormat
  ),
  transports: [new transports.Console()]
});

To see what built-in formats are available and learn more about creating your own custom logging formats, see [logform][logform].

Combining formats

Any number of formats may be combined into a single format using format.combine. Since format.combine takes no opts, as a convenience it returns pre-created instance of the combined format.

javascript
const { createLogger, format, transports } = require('winston');
const { combine, timestamp, label, prettyPrint } = format;

const logger = createLogger({
  format: combine(
    label({ label: 'right meow!' }),
    timestamp(),
    prettyPrint()
  ),
  transports: [new transports.Console()]
})

logger.log({
  level: 'info',
  message: 'What time is the testing at?'
});
// Outputs:
// { level: 'info',
//   message: 'What time is the testing at?',
//   label: 'right meow!',
//   timestamp: '2017-09-30T03:57:26.875Z' }

String interpolation

The log method provides the string interpolation using [util.format]. It must be enabled using format.splat().

Below is an example that defines a format with string interpolation of messages using format.splat and then serializes the entire info message using format.simple.

javascript
const { createLogger, format, transports } = require('winston');
const logger = createLogger({
  format: format.combine(
    format.splat(),
    format.simple()
  ),
  transports: [new transports.Console()]
});

// info: test message my string {}
logger.log('info', 'test message %s', 'my string');

// info: test message 123 {}
logger.log('info', 'test message %d', 123);

// info: test message first second {number: 123}
logger.log('info', 'test message %s, %s', 'first', 'second', { number: 123 });

Filtering info Objects

If you wish to filter out a given info Object completely

Issues· 535 open

View all issuesOpen on GitHub
  • #2440

    Status on async/await custom transport support?

    Needs InvestigationBugUpdated Aug 26, 2026
  • #1825

    Winston not creating any output when running in a Docker container

    Updated Aug 11, 2026
  • #2602

    [Bug]: exitWithError not failing Playwright test

    Needs InvestigationBugUpdated Aug 5, 2026
  • #2116

    [Feature Request]: obfuscation of values that is PII or PCI data

    Needs InvestigationFeature RequestUpdated Aug 5, 2026
  • #1118

    Document Http transfer

    DocsHelp WantedUpdated Jul 22, 2026
  • #2162

    [Bug]: default metadata is not added on log message of profiler

    Needs InvestigationBugUpdated Jul 7, 2026
  • #2623

    [Feature Request][Maintainer Offer]: winston-couchdb

    Needs InvestigationFeature RequestUpdated Jul 2, 2026
  • #1573

    File logging reconfiguration issue (Error: write after end)

    BugImportantGood First IssueHelp WantedUpdated Jun 17, 2026
  • #2586

    [Bug]: winston3.3.3 resolves to @dabh/diagnostics@^2 → pulls @so-ric/colorspace (ES2021 ||=) and crashes on Node 12

    Updated May 19, 2026
  • #2381

    [Bug]: Child logger changes Error object type to plain which cause the info object to bypass error() formatter

    Needs InvestigationBugUpdated Apr 11, 2026

> Tags

JavaScript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 30, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言