docs/transports.md
In winston a transport is essentially a storage device for your logs. Each
instance of a winston logger can have multiple transports configured at
different 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.
There are several core transports included in winston
that leverage the built-in networking and file I/O offered by Node.js core. In
addition, there are transports which are actively supported by winston
contributors. And last (but not least)
there are additional transports written by
members of the community.
Additionally there are transports previously maintained by winston contributors that are looking for maintainers.
There are several core transports included in winston, which leverage the built-in networking and file I/O offered by Node.js core.
logger.add(new winston.transports.Console(options));
The Console transport takes a few simple options:
os.EOL)['error', 'debug', 'info']. (default [])['warn', 'debug']. (default [])logger.add(new winston.transports.File(options));
The File transport supports a variety of file writing options. If you are looking for daily log rotation see DailyRotateFile
os.EOL).fs.createWriteStream (default {flags: 'a'}).logger.add(new winston.transports.Http(options));
The Http transport is a generic way to log, query, and stream logs from an arbitrary Http endpoint, preferably winstond. It takes options that are passed to the node.js http or https request:
username and password for HTTP Basic Authlogger.add(new winston.transports.Stream({
stream: fs.createWriteStream('/dev/null')
/* other options */
}));
The Stream transport takes a few simple options:
objectMode stream is provided then
the entire info object will be written. Otherwise info[MESSAGE] will be
written.os.EOL).Starting with [email protected] an effort was made to remove any transport which added additional dependencies to winston. At the time there were several transports already in winston which will have slowly waned in usage. The
following transports are actively maintained by members of the winston Github
organization.
As of [email protected] the MongoDB transport has been broken out into a new module: winston-mongodb. Using it is just as easy:
const winston = require('winston');
/**
* Requiring `winston-mongodb` will expose
* `winston.transports.MongoDB`
*/
require('winston-mongodb');
logger.add(new winston.transports.MongoDB(options));
The MongoDB transport takes the following options. 'db' is required:
{poolSize: 2, autoReconnect: true}).Metadata: Logged as a native JSON object in 'meta' property.
Logging unhandled exceptions: For logging unhandled exceptions specify
winston-mongodb as handleExceptions logger according to winston documentation.
See winston-syslog.
The community has truly embraced winston; there are over 23 winston transports and over half of them are maintained by authors external to the winston core team. If you want to check them all out, just search npm:
$ npm search winston
If you have an issue using one of these modules you should contact the module author directly
winston-airbrake2 is a transport for winston that sends your logs to Airbrake.io.
const winston = require('winston');
const { Airbrake } = require('winston-airbrake2');
logger.add(new Airbrake(options));
The Airbrake transport utilises the node-airbrake module to send logs to the Airbrake.io API. You can set the following options:
The winston-aws-cloudwatch transport relays your log messages to Amazon CloudWatch.
const winston = require('winston');
const AwsCloudWatch = require('winston-aws-cloudwatch');
logger.add(new AwsCloudWatch(options));
Options:
accessKeyId, secretAccessKey, region, etc.Alternatively, you may be interested in winston-cloudwatch.
lazywithclass/winston-cloudwatch is no longer maintained. Use
@initd-sg/winston-cloudwatch
The winston-dynamodb transport uses Amazon's DynamoDB as a sink for log messages. You can take advantage of the various authentication methods supports by Amazon's aws-sdk module. See Configuring the SDK in Node.js.
const winston = require('winston');
const { DynamoDB } = require('winston-dynamodb');
logger.add(new DynamoDB(options));
Options:
To Configure using environment authentication:
logger.add(new winston.transports.DynamoDB({
useEnvironment: true,
tableName: 'log'
}));
Also supports callbacks for completion when the DynamoDB putItem has been completed.
The winston-firehose transport relays your log messages to Amazon Kinesis Firehose.
const winston = require('winston');
const WFirehose = require('winston-firehose');
logger.add(new WFirehose(options));
Options:
The winston-sns transport uses amazon SNS to send emails, texts, or a bunch of other notifications. Since this transport uses the Amazon AWS SDK for JavaScript, you can take advantage of the various methods of authentication found in Amazon's Configuring the SDK in Node.js document.
const winston = require('winston');
const SnsTransport = require('winston-sns');
logger.add(new SnsTransport(options));
Options:
us-east-1,us-west-1,eu-west-1,ap-southeast-1,ap-northeast-1,us-gov-west-1,sa-east-1. (default: us-east-1)info)false)false)winston-azuretable is a Azure Table transport:
const { AzureLogger } = require('winston-azuretable');
logger.add(new AzureLogger(options));
The Azure Table transport connects to an Azure Storage Account using the following options:
false)AZURE_STORAGE_ACCOUNTAZURE_STORAGE_ACCESS_KEYinfo)log)process.env.NODE_ENV)false)winston-cassandra is a Cassandra transport:
const Cassandra = require('winston-cassandra').Cassandra;
logger.add(new Cassandra(options));
The Cassandra transport connects to a cluster using the native protocol with the following options:
'info').'logs').'hour' and 'day'(Default).quorum).In addition to the options accepted by the Node.js Cassandra driver Client.
['host1', 'host2'] (required).winston-spark is a transport for Cisco Spark
const winston = require('winston');
require('winston-spark');
const options = {
accessToken: '***Your Spark Access Token***',
roomId: '***Spark Room Id***'
};
logger.add(new winston.transports.SparkLogger(options));
Valid Options are as the following:
winston-clodant is a transport for Cloudant NoSQL Db.
const winston = require('winston');
const WinstonCloudant = require('winston-cloudant');
logger.add(new WinstonCloudant(options));
The Cloudant transport takes the following options:
url : Access url including user and password [required]
username : Username for the Cloudant DB instance
password : Password for the Cloudant DB instance
host : Host for the Cloudant DB instance
db : Name of the databasename to put logs in
logstash : Write logs in logstash format
datadog-logger-integrations is a transport to ship your logs to DataDog.
var winston = require('winston')
var { DataDogTransport } = require('datadog-logger-integrations/winston')
var logger = winston.createLogger({
// Whatever options you need
// Refer https://github.com/winstonjs/winston#creating-your-own-logger
})
logger.add(
new DataDogTransport({
ddClientConfig: {
authMethods: {
apiKeyAuth: apiKey,
},
},
service: 'super_service',
ddSource: 'nodejs',
ddTags: 'foo:bar,boo:baz'
})
)
Options:
winston-bigquery is a transport for Google BigQuery.
import {WinstonBigQuery} from 'winston-bigquery';
import winston, {format} from 'winston';
const logger = winston.createLogger({
transports: [
new WinstonBigQuery({
tableId: 'winston_logs',
datasetId: 'logs'
})
]
});
The Google BigQuery takes the following options:
Pay Attention, since BQ, unlike some other products, is not a "schema-less" you will need to build the schema in advance. read more on the topic on github or npmjs.com
@google-cloud/logging-winston provides a transport to relay your log messages to Stackdriver Logging.
const winston = require('winston');
const Stackdriver = require('@google-cloud/logging-winston');
logger.add(new Stackdriver({
projectId: 'your-project-id',
keyFilename: '/path/to/keyfile.json'
}));
winston-graylog2 is a Graylog2 transport:
const winston = require('winston');
const Graylog2 = require('winston-graylog2');
logger.add(new Graylog2(options));
The Graylog2 transport connects to a Graylog2 server over UDP using the following options:
Log to Elasticsearch in a logstash-like format and leverage Kibana to browse your logs.
See: https://github.com/vanthome/winston-elasticsearch.
fast-file-rotate is a performant file transport providing daily log rotation.
const FileRotateTransport = require('fast-file-rotate');
const winston = require('winston');
const logger = winston.createLogger({
transports: [
new FileRotateTransport({
fileName: __dirname + '/console%DATE%.log'
})
]
})
humio-winston is a transport for sending logs to Humio:
const winston = require('winston');
const HumioTransport = require('humio-winston');
const logger = winston.createLogger({
transports: [
new HumioTransport({
ingestToken: '<YOUR HUMIO INGEST TOKEN>',
}),
],
});
LogDNA Winston is a transport for being able to forward the logs to LogDNA:
const logdnaWinston = require('logdna-winston');
const winston = require('winston');
const logger = winston.createLogger({});
const options = {
key: apikey, // the only field required
hostname: myHostname,
ip: ipAddress,
mac: macAddress,
app: appName,
env: envName,
index_meta: true // Defaults to false, when true ensures meta object will be searchable
};
// Only add this line in order to track exceptions
options.handleExceptions = true;
logger.add(new logdnaWinston(options));
let meta = {
data:'Some information'
};
logger.log('info', 'Log from LogDNA Winston', meta);
You can download the logzio transport here : https://github.com/logzio/winston-logzio
Basic Usage
const winston = require('winston');
const Logzio = require('winston-logzio');
logger.add(new Logzio({
token: '__YOUR_API_TOKEN__'
}));
For more information about how to configure the logzio transport, view the README.md in the winston-logzio repo.
winston-logsene transport for Elasticsearch bulk indexing via HTTPS to Logsene:
const winston = require('winston');
const Logsene = require('winston-logsene');
logger.add(new Logsene({
token: process.env.LOGSENE_TOKEN
/* other options */
}));
Options:
Logsene features:
The winston-mail is an email transport:
const { Mail } = require('winston-mail');
logger.add(new Mail(options));
The Mail transport uses node-mail behind the scenes. Options are the following, to and host are required:
winston@[server-host-name])Metadata: Stringified as JSON in email.
winston-mysql is a MySQL transport for Winston.
Create a table in your database first:
CREATE TABLE `sys_logs_default` (
`id` INT NOT NULL AUTO_INCREMENT,
`level` VARCHAR(16) NOT NULL,
`message` VARCHAR(2048) NOT NULL,
`meta` VARCHAR(2048) NOT NULL,
`timestamp` DATETIME NOT NULL,
PRIMARY KEY (`id`));
You can also specify
metato be aJSONfield on MySQL 5.7+, i.e., ``metaJSON NOT NULL, which is helfpul for searching and parsing.
Configure Winston with the transport:
import MySQLTransport from 'winston-mysql';
const options = {
host: '${MYSQL_HOST}',
user: '${MYSQL_USER}',
password: '${MYSQL_PASSWORD}',
database: '${MYSQL_DATABASE}',
table: 'sys_logs_default'
};
const logger = winston.createLogger({
level: 'debug',
format: winston.format.json(),
defaultMeta: { service: 'user-service' },
transports: [
new winston.transports.Console({
format: winston.format.simple(),
}),
new MySQLTransport(options),
],
});
/// ...
let msg = 'My Log';
logger.info(msg, {message: msg, type: 'demo'});
winston-newrelic-agent-transport is a New Relic transport that leverages the New Relic agent:
import winston from 'winston'
import NewrelicTransport from 'winston-newrelic-agent-transport'
const logger = winston.createLogger()
const options = {}
logger.add(new NewrelicTransport(options))
The New Relic agent typically automatically forwards Winston logs to New Relic when using CommonJS. With CommonJS no additional transport should be needed. However, when using ECMAScript modules, the automatic forwarding of logs can with certain coding patterns not work. If the New Relic agent is not automatically forwarding your logs, this transport provides a solution.
Options:
winston-papertrail is a Papertrail transport:
const { Papertrail } = require('winston-papertrail');
logger.add(new Papertrail(options));
The Papertrail transport connects to a PapertrailApp log destination over TCP (TLS) using the following options:
function(level, message), which allows custom formatting of the level or message prior to deliveryMetadata: Logged as a native JSON object to the 'meta' attribute of the item.
Parseable is an open source, general purpose log analytics system. Parseable-Winston is a Parseable transport for Winston.
// Using cjs
const { ParseableTransport } = require('parseable-winston')
const winston = require('winston')
const parseable = new ParseableTransport({
url: process.env.PARSEABLE_LOGS_URL, // Ex: 'https://parsable.myserver.local/api/v1/logstream'
username: process.env.PARSEABLE_LOGS_USERNAME,
password: process.env.PARSEABLE_LOGS_PASSWORD,
logstream: process.env.PARSEABLE_LOGS_LOGSTREAM, // The logstream name
tags: { tag1: 'tagValue' } // optional tags to be added with each ingestion
})
const logger = winston.createLogger({
levels: winston.config.syslog.levels,
transports: [parseable],
defaultMeta: { instance: 'app', hostname: 'app1' }
})
logger.info('User took the goggles', { userid: 1, user: { name: 'Rainier Wolfcastle' } })
logger.warning('The goggles do nothing', { userid: 1 })
@pauleliet/winston-pg-native is a PostgresQL transport supporting Winston 3.X.
winston-pusher is a Pusher transport.
const { PusherLogger } = require('winston-pusher');
logger.add(new PusherLogger(options));
This transport sends the logs to a Pusher app for real time processing and it uses the following options:
winston-transport-sentry-node is a transport for Sentry uses @sentry/node.
const Sentry = require('winston-transport-sentry-node').default;
logger.add(new Sentry({
sentry: {
dsn: 'https://******@sentry.io/12345',
},
level: 'info'
}));
This transport takes the following options:
process.env.SENTRY_DSN) REQUIREDprocess.env.SENTRY_ENVIRONMENT || process.env.NODE_ENV || 'production')process.env.SENTRY_DEBUG || false)1.0)100)winston-seq is a transport that sends structured log events to Seq.
const { SeqTransport } = require('@datalust/winston-seq');
logger.add(new SeqTransport({
serverUrl: "https://your-seq-server:5341",
apiKey: "your-api-key",
onError: (e => { console.error(e) }),
}));
SeqTransport is configured with the following options:
The winston-simpledb transport is just as easy:
const SimpleDB = require('winston-simpledb').SimpleDB;
logger.add(new SimpleDB(options));
The SimpleDB transport takes the following options. All items marked with an asterisk are required:
Metadata: Logged as a native JSON object to the 'meta' attribute of the item.
winston-slack-webhook-transport is a transport that sends all log messages to the Slack chat service.
const winston = require('winston');
const SlackHook = require('winston-slack-webhook-transport');
const logger = winston.createLogger({
level: 'info',
transports: [
new SlackHook({
webhookUrl: 'https://hooks.slack.com/services/xxx/xxx/xxx'
})
]
});
logger.info('This should now appear on Slack');
This transport takes the following options:
[level]: [message] with no attachments or layout blocks.mrkdwn formatting within attachments or layout blocks (Default: false)The winston-better-sqlite3 transport uses better-sqlite3.
const wbs = require('winston-better-sqlite3');
logger.add(new wbs({
// path to the sqlite3 database file on the disk
db: '<name of sqlite3 database file>',
// A list of params to log
params: ['level', 'message']
}));
winston-sumologic-transport is a transport for Sumo Logic
const winston = require('winston');
const { SumoLogic } = require('winston-sumologic-transport');
logger.add(new SumoLogic(options));
Options:
winston-koa-sse is a transport that leverages on Server Sent Event. With this transport you can use your browser console to view your server logs.
winston-transport-vscode is a transport for VS Code extension development.
const vscode = require('vscode');
const winston = require('winston');
const { OutputChannelTransport } = require('winston-transport-vscode');
const outputChannel = vscode.window.createOutputChannel('My extension');
const logger = winston.createLogger({
transports: [new OutputChannelTransport({ outputChannel })],
});
The extension includes dedicated log levels and format for using with VS Code's LogOutputChannel.
const { LogOutputChannelTransport } = require('winston-transport-vscode');
const outputChannel = vscode.window.createOutputChannel('My extension', {
log: true,
});
const logger = winston.createLogger({
levels: LogOutputChannelTransport.config.levels,
format: LogOutputChannelTransport.format(),
transports: [new LogOutputChannelTransport({ outputChannel })],
});
winston-console-transport-in-worker
import * as winston from 'winston';
import { ConsoleTransportInWorker } from '@greeneyesai/winston-console-transport-in-worker';
...
export const logger: winston.Logger = winston.createLogger({
format: combine(timestamp(), myFormat),
level: Level.INFO,
transports: [new ConsoleTransportInWorker()],
});
The ConsoleTransportInWorker is a subclass of winston.transports.Console therefore accepting the same options as the Console transport.
TypeScript supported.
winston-winlog2 is a Windows Event log transport:
const winston = require('winston');
const Winlog2 = require('winston-winlog2');
logger.add(new Winlog2(options));
The winlog2 transport uses the following options:
These transports are part of the winston Github organization but are
actively seeking new maintainers. Interested in getting involved? Open an
issue on winston to get the conversation started!
As of [email protected] the CouchDB transport has been broken out into a new module: winston-couchdb.
const WinstonCouchDb = require('winston-couchdb');
logger.add(new WinstonCouchdb(options));
The Couchdb will place your logs in a remote CouchDB database. It will also create a Design Document, _design/Logs for later querying and streaming your logs from CouchDB. The transport takes the following options:
username and password for HTTP Basic AuthAs of [email protected] the Loggly transport has been broken out into a new module: winston-loggly.
const WinstonLoggly = require('winston-loggly');
logger.add(new winston.transports.Loggly(options));
The Loggly transport is based on Nodejitsu's node-loggly implementation of the Loggly API. If you haven't heard of Loggly before, you should probably read their value proposition. The Loggly transport takes the following options. Either 'inputToken' or 'inputName' is required:
const WinstonRedis = require('winston-redis');
logger.add(new WinstonRedis(options));
This transport accepts the options accepted by the node-redis client:
In addition to these, the Redis transport also accepts the following options.
As of [email protected] the Riak transport has been broken out into a new module: winston-riak. Using it is just as easy:
const { Riak } = require('winston-riak');
logger.add(new Riak(options));
In addition to the options accepted by the riak-js client, the Riak transport also accepts the following options. It is worth noting that the riak-js debug option is set to false by default:
// Use a single bucket for all your logs
const singleBucketTransport = new Riak({ bucket: 'some-logs-go-here' });
// Generate a dynamic bucket based on the date and level
const dynamicBucketTransport = new Riak({
bucket: function (level, msg, meta, now) {
var d = new Date(now);
return level + [d.getDate(), d.getMonth(), d.getFullYear()].join('-');
}
});
There are more than 1000 packages on npm when you search for winston.
That's why we say it's a logger for just about everything