### Example: Configure Exception Handlers and Exit Behavior Source: https://github.com/winstonjs/winston/blob/master/README.md Demonstrates configuring both specific exception handlers and the `exitOnError` behavior when creating a logger. This setup logs exceptions to a dedicated file and prevents exiting on all errors. ```js const logger = winston.createLogger({ transports: [ new winston.transports.File({ filename: 'path/to/combined.log' }) ], exceptionHandlers: [ new winston.transports.File({ filename: 'path/to/exceptions.log' }) ] }); ``` -------------------------------- ### Install Winston using npm Source: https://github.com/winstonjs/winston/blob/master/README.md Use this command to install the Winston logging library via npm. ```bash npm install winston ``` -------------------------------- ### Install Winston using yarn Source: https://github.com/winstonjs/winston/blob/master/README.md Use this command to install the Winston logging library via yarn. ```bash yarn add winston ``` -------------------------------- ### Start and Stop Profiling with Winston Source: https://github.com/winstonjs/winston/blob/master/README.md Use the `logger.profile()` method to start and stop a timer for a given label. The duration will be logged automatically. ```js // // Start profile of 'test' // logger.profile('test'); setTimeout(function () { // // Stop profile of 'test'. Logging will now take place: // '17 Jan 21:00:00 - info: test duration=1000ms' // logger.profile('test'); }, 1000); ``` -------------------------------- ### Winston 3.0 Modularity Example Source: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md Demonstrates the modular structure of Winston v3.0, utilizing `winston-transport` and `logform` for custom formatting and transport configuration. ```javascript const { createLogger, transports, format } = require('winston'); const Transport = require('winston-transport'); const logform = require('logform'); const { combine, timestamp, label, printf } = logform.format; // winston.format is require('logform') console.log(logform.format === format) // true const logger = createLogger({ format: combine( label({ label: 'right meow!' }), timestamp(), printf(nfo => { return `${nfo.timestamp} [${nfo.label}] ${nfo.level}: ${nfo.message}`; }) ), transports: [new transports.Console()] }); ``` -------------------------------- ### Stream Logs from Winston Source: https://github.com/winstonjs/winston/blob/master/README.md Stream logs from a Winston transport. This example starts streaming from the end of the log. ```js // // Start at the end. // winston.stream({ start: -1 }).on('log', function(log) { console.log(log); }); ``` -------------------------------- ### Add Distribution Tag Source: https://github.com/winstonjs/winston/blob/master/docs/publishing.md After publishing, add a distribution tag to the new version. This example adds the '3.x-latest' tag to version '3.7.0'. ```bash npm dist-tag add winston@3.7.0 3.x-latest ``` -------------------------------- ### Create and Configure a Winston Logger Source: https://github.com/winstonjs/winston/blob/master/README.md Use `winston.createLogger` to set up a logger with specific levels, formats, and transports. This example configures file transports for errors and combined logs, and a console transport for development environments. ```js const winston = require('winston'); const logger = winston.createLogger({ level: 'info', format: winston.format.json(), defaultMeta: { service: 'user-service' }, transports: [ // // - Write all logs with importance level of `error` or higher to `error.log` // (i.e., error, fatal, but not other levels) // new winston.transports.File({ filename: 'error.log', level: 'error' }), // // - Write all logs with importance level of `info` or higher to `combined.log` // (i.e., fatal, error, warn, and info, but not trace) // new winston.transports.File({ filename: 'combined.log' }), ], }); // // If we're not in production then log to the `console` with the format: // `${info.level}: ${info.message} JSON.stringify({ ...rest }) ` // if (process.env.NODE_ENV !== 'production') { logger.add(new winston.transports.Console({ format: winston.format.simple(), })); } ``` -------------------------------- ### Manual Profiling with Timer Reference Source: https://github.com/winstonjs/winston/blob/master/README.md Start a timer using `logger.startTimer()` and manually stop it by calling `.done()` on the returned profiler object, optionally logging additional metadata. ```js // Returns an object corresponding to a specific timing. When done // is called the timer will finish and log the duration. e.g.: // const profiler = logger.startTimer(); setTimeout(function () { profiler.done({ message: 'Logging message' }); }, 1000); ``` -------------------------------- ### Example: Console Transport with Exception Handling and No Exit Source: https://github.com/winstonjs/winston/blob/master/README.md Illustrates using a Console transport with exception handling enabled and setting `exitOnError` to `false`. This configuration logs exceptions to the console and ensures the process does not exit automatically. ```js const logger = winston.createLogger({ transports: [ new winston.transports.Console({ handleExceptions: true }) ], exitOnError: false }); ``` -------------------------------- ### Migrate winston@2 rewriter to winston@3 format Source: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md This example demonstrates converting a winston@2 rewriter function into a custom winston@3 format. Custom formats can be used to add or modify properties within the log object. ```javascript const logger = new winston.Logger(options); logger.rewriters.push(function(level, msg, meta) { if (meta.creditCard) { meta.creditCard = maskCardNumbers(meta.creditCard) } return meta; }); logger.info('transaction ok', { creditCard: 123456789012345 }); ``` ```javascript const maskFormat = winston.format(info => { // You can CHANGE existing property values if (info.creditCard) { info.creditCard = maskCardNumbers(info.creditCard); } // You can also ADD NEW properties if you wish info.hasCreditCard = !!info.creditCard; return info; }); const logger = winston.createLogger({ format: winston.format.combine( maskFormat(), winston.format.json() ) }); logger.info('transaction ok', { creditCard: 123456789012345 }); ``` -------------------------------- ### Add MongoDB Transport to Winston Logger Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Demonstrates how to require the winston-mongodb module and add a MongoDB transport to a Winston logger instance. Ensure winston-mongodb is installed as a dependency. ```js const winston = require('winston'); /** * Requiring `winston-mongodb` will expose * `winston.transports.MongoDB` */ require('winston-mongodb'); logger.add(new winston.transports.MongoDB(options)); ``` -------------------------------- ### Add Airbrake Transport to Winston Logger Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Integrate the Airbrake transport to send logs to Airbrake.io. Ensure the 'winston-airbrake2' package is installed. ```javascript const winston = require('winston'); const { Airbrake } = require('winston-airbrake2'); logger.add(new Airbrake(options)); ``` -------------------------------- ### Migrate winston@2 filter to winston@3 format Source: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md This example shows how to convert a winston@2 filter function into a custom winston@3 format. Use custom formats to modify log message content before it's logged. ```javascript const isSecret = /super secret/; const logger = new winston.Logger(options); logger.filters.push(function(level, msg, meta) { return msg.replace(isSecret, 'su*** se****'); }); // Outputs: {"level":"error","message":"Public error to share"} logger.error('Public error to share'); // Outputs: {"level":"error","message":"This is su*** se**** - hide it."} logger.error('This is super secret - hide it.'); ``` ```javascript const { createLogger, format, transports } = require('winston'); // Ignore log messages if the have { private: true } const isSecret = /super secret/; const filterSecret = format((info, opts) => { info.message = info.message.replace(isSecret, 'su*** se****'); return info; }); const logger = createLogger({ format: format.combine( filterSecret(), format.json() ), transports: [new transports.Console()] }); // Outputs: {"level":"error","message":"Public error to share"} logger.log({ level: 'error', message: 'Public error to share' }); // Outputs: {"level":"error","message":"This is su*** se**** - hide it."} logger.log({ level: 'error', message: 'This is super secret - hide it.' }); ``` -------------------------------- ### Publish to npm Source: https://github.com/winstonjs/winston/blob/master/docs/publishing.md After completing all release preparation steps, use this command to publish the new version to the npm registry. You may need to complete npm 2FA. ```bash npm publish ``` -------------------------------- ### Using Winston Logger Levels Source: https://github.com/winstonjs/winston/blob/master/README.md Demonstrates how to log messages using string level names or level-specific methods on a logger instance. Also shows logging with the default winston logger. ```js // // Any logger instance // logger.log('silly', "127.0.0.1 - there's no place like home"); logger.log('debug', "127.0.0.1 - there's no place like home"); logger.log('verbose', "127.0.0.1 - there's no place like home"); logger.log('info', "127.0.0.1 - there's no place like home"); logger.log('warn', "127.0.0.1 - there's no place like home"); logger.log('error', "127.0.0.1 - there's no place like home"); logger.info("127.0.0.1 - there's no place like home"); logger.warn("127.0.0.1 - there's no place like home"); logger.error("127.0.0.1 - there's no place like home"); // // Default logger // winston.log('info', "127.0.0.1 - there's no place like home"); winston.info("127.0.0.1 - there's no place like home"); ``` -------------------------------- ### Create Winston Logger Instance Source: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md Use `winston.createLogger(opts)` instead of `new winston.Logger(opts)` for improved performance and to avoid deprecated methods. ```javascript const logger = winston.createLogger(options); ``` -------------------------------- ### Winston Logger Initialization with Custom Format Source: https://github.com/winstonjs/winston/blob/master/CONTRIBUTING.md Demonstrates how to create a Winston logger instance with a custom format combining labels, timestamps, and a printf function. This logger uses the Console transport. ```javascript const { createLogger, transports, format } = require('winston'); const Transport = require('winston-transport'); const logform = require('logform'); const { combine, timestamp, label, printf } = logform.format; // winston.format is require('logform') console.log(logform.format === format) // true const logger = createLogger({ format: combine( label({ label: 'right meow!' }), timestamp(), printf(({ level, message, label, timestamp }) => { return `${timestamp} [${label}] ${level}: ${message}`; }) ), transports: [new transports.Console()] }); ``` -------------------------------- ### Configure Winston for Google BigQuery Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Set up Winston to log to Google BigQuery using the `winston-bigquery` transport. You must specify `datasetId` and `tableId`. For development, `applicationCredentials` can point to a local service account file. Note that BigQuery requires a pre-defined schema. ```javascript import {WinstonBigQuery} from 'winston-bigquery'; import winston, {format} from 'winston'; const logger = winston.createLogger({ transports: [ new WinstonBigQuery({ tableId: 'winston_logs', datasetId: 'logs' }) ] }); ``` -------------------------------- ### Log Messages with Winston Source: https://github.com/winstonjs/winston/blob/master/README.md Demonstrates how to log messages at a specific level or using convenience methods. Ensure the logger has appropriate transports configured. ```js // // Logging // logger.log({ level: 'info', message: 'Hello distributed log files!' }); logger.info('Hello again distributed logs'); ``` -------------------------------- ### Create a Winston Logger Source: https://github.com/winstonjs/winston/blob/master/README.md Initializes a new Winston logger instance with specified transports. Ensure transports are correctly configured before use. ```js const logger = winston.createLogger({ transports: [ new winston.transports.Console(), new winston.transports.File({ filename: 'combined.log' }) ] }); ``` -------------------------------- ### Configure Winston with MySQL Transport Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Initializes Winston with a MySQL transport, specifying connection details and table name. Includes console transport for local debugging. ```javascript 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'}); ``` -------------------------------- ### Add Sumo Logic Transport to Winston Logger Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Configure the Sumo Logic transport for Winston by providing the Sumo Logic HTTP collector URL. ```js const winston = require('winston'); const { SumoLogic } = require('winston-sumologic-transport'); logger.add(new SumoLogic(options)); ``` -------------------------------- ### Configure Winston with FastFileRotate Transport Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Implement daily log rotation with the `fast-file-rotate` transport for Winston. Specify the `fileName` pattern, which includes a date token for rotation. ```javascript const FileRotateTransport = require('fast-file-rotate'); const winston = require('winston'); const logger = winston.createLogger({ transports: [ new FileRotateTransport({ fileName: __dirname + '/console%DATE%.log' }) ] }) ``` -------------------------------- ### Add Graylog2 Transport to Winston Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Configure Winston to send logs to a Graylog2 server via UDP using the `winston-graylog2` transport. The `options` object should include `graylog.servers` with host and port, and can optionally specify `level`, `silent`, `handleExceptions`, `hostname`, `facility`, and `bufferSize`. ```javascript const winston = require('winston'); const Graylog2 = require('winston-graylog2'); logger.add(new Graylog2(options)); ``` -------------------------------- ### Query Logs with Options Source: https://github.com/winstonjs/winston/blob/master/README.md Use this snippet to query logs within a specified date range, with options for limiting, ordering, and selecting fields. Ensure logger is configured. ```js const options = { from: new Date() - (24 * 60 * 60 * 1000), until: new Date(), limit: 10, start: 0, order: 'desc', fields: ['message'] }; // // Find items logged between today and yesterday. // logger.query(options, function (err, results) { if (err) { /* TODO: handle me */ throw err; } console.log(results); }); ``` -------------------------------- ### Winston Symbol Constants from triple-beam Source: https://github.com/winstonjs/winston/blob/master/README.md Shows how to import and use Symbol constants (LEVEL, MESSAGE, SPLAT) from the 'triple-beam' package, which are used internally by Winston for managing log message state. ```js 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 ``` -------------------------------- ### Configure Parseable Transport for Winston Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Sets up the Parseable transport for Winston, sending logs to a Parseable log analytics system. Ensure environment variables for URL, username, password, and logstream are set. ```js // 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 }) ``` -------------------------------- ### Create Custom Log Format with printf Source: https://github.com/winstonjs/winston/blob/master/README.md Define a custom log message format using `winston.format.printf`. This is useful for bespoke formatting of log output. Ensure `label` and `timestamp` are included in the format combination if needed. ```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()] }); ``` -------------------------------- ### Colorizing Standard Log Levels Source: https://github.com/winstonjs/winston/blob/master/README.md Combines the 'colorize' formatter with the 'simple' formatter to enable colored output for standard log levels. The 'colorize' formatter should precede others that add text. ```js winston.format.combine( winston.format.colorize(), winston.format.simple() ); ``` -------------------------------- ### List Distribution Tags Source: https://github.com/winstonjs/winston/blob/master/docs/publishing.md Verify that the distribution tags have been added correctly using this command. This lists all tags for the winston package. ```bash npm dist-tag ls ``` -------------------------------- ### Configuring Transports with Specific Levels Source: https://github.com/winstonjs/winston/blob/master/README.md Sets up a logger with console and file transports, each configured to log messages up to a specific level (error for console, info for file). ```js const logger = winston.createLogger({ levels: winston.config.syslog.levels, transports: [ new winston.transports.Console({ level: 'error' }), new winston.transports.File({ filename: 'combined.log', level: 'info' }) ] }); ``` -------------------------------- ### Search for Winston Transports on npm Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Use npm search to find available community transports for Winston. ```bash $ npm search winston ``` -------------------------------- ### Configure Multiple File Transports Source: https://github.com/winstonjs/winston/blob/master/README.md Set up a Winston logger with multiple transports of the same type (e.g., File) to direct logs to different files based on their level. This allows for segregated log storage. ```js const logger = winston.createLogger({ transports: [ new winston.transports.File({ filename: 'combined.log', level: 'info' }), new winston.transports.File({ filename: 'errors.log', level: 'error' }) ] }); ``` -------------------------------- ### Add Google Stackdriver Transport to Winston Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Integrate Winston with Google Stackdriver Logging using the `@google-cloud/logging-winston` package. Provide your `projectId` and the `keyFilename` for authentication. ```javascript const winston = require('winston'); const Stackdriver = require('@google-cloud/logging-winston'); logger.add(new Stackdriver({ projectId: 'your-project-id', keyFilename: '/path/to/keyfile.json' })); ``` -------------------------------- ### Add Humio Transport to Winston Logger Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Integrate Winston with Humio for log ingestion using the `humio-winston` transport. You must provide your Humio `ingestToken` in the transport options. ```javascript const winston = require('winston'); const HumioTransport = require('humio-winston'); const logger = winston.createLogger({ transports: [ new HumioTransport({ ingestToken: '', }), ], }); ``` -------------------------------- ### Dynamically Changing Transport Log Levels Source: https://github.com/winstonjs/winston/blob/master/README.md Initializes a logger with console and file transports, then demonstrates how to dynamically change the log level for each transport after creation. ```js const transports = { console: new winston.transports.Console({ level: 'warn' }), file: new winston.transports.File({ filename: 'combined.log', level: 'error' }) }; const logger = winston.createLogger({ transports: [ transports.console, transports.file ] }); logger.info('Will not be logged in either transport!'); transports.console.level = 'info'; transports.file.level = 'info'; logger.info('Will be logged in both transports!'); ``` -------------------------------- ### Configuring Multiple Loggers in Winston Source: https://github.com/winstonjs/winston/blob/master/README.md Manage multiple logger instances with different configurations for distinct application areas using `winston.loggers.add()` or `winston.Container`. ```js const winston = require('winston'); const { format } = winston; const { combine, label, json } = format; // // Configure the logger for `category1` // winston.loggers.add('category1', { format: combine( label({ label: 'category one' }), json() ), transports: [ new winston.transports.Console({ level: 'silly' }), new winston.transports.File({ filename: 'somefile.log' }) ] }); // // Configure the logger for `category2` // winston.loggers.add('category2', { format: combine( label({ label: 'category two' }), json() ), transports: [ new winston.transports.Http({ host: 'localhost', port:8080 }) ] }); ``` ```js const winston = require('winston'); // // Grab your preconfigured loggers // const category1 = winston.loggers.get('category1'); const category2 = winston.loggers.get('category2'); category1.info('logging to file and console transports'); category2.info('logging to http transport'); ``` ```js const winston = require('winston'); const { format } = winston; const { combine, label, json } = format; const container = new winston.Container(); container.add('category1', { format: combine( label({ label: 'category one' }), json() ), transports: [ new winston.transports.Console({ level: 'silly' }), new winston.transports.File({ filename: 'somefile.log' }) ] }); const category1 = container.get('category1'); category1.info('logging to file and console transports'); ``` -------------------------------- ### Add SimpleDB Transport to Winston Logger Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Instantiate and add the SimpleDB transport to your Winston logger. Ensure all required options like AWS credentials and domain information are provided. ```js const SimpleDB = require('winston-simpledb').SimpleDB; logger.add(new SimpleDB(options)); ``` -------------------------------- ### Configure LogDNA Transport for Winston Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Forward logs to LogDNA using the `logdna-winston` transport. The `key` is required, and other options like `hostname`, `ip`, `mac`, `app`, `env`, and `index_meta` can be provided for enhanced log data. `handleExceptions` can be set to `true` to track exceptions. ```javascript 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); ``` -------------------------------- ### Create MySQL Table for Winston Logs Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md SQL schema for a table to store Winston logs in a MySQL database. Supports 'meta' as JSON for MySQL 5.7+. ```sql 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`)); ``` -------------------------------- ### Create and Use Custom Winston Log Format Source: https://github.com/winstonjs/winston/blob/master/README.md Defines a custom log format that can optionally convert messages to uppercase or lowercase based on provided options. Demonstrates creating format instances with specific configurations and transforming log info objects. ```javascript const { format } = require('winston'); const volume = format((info, opts) => { if (opts.yell) { info.message = info.message.toUpperCase(); } else if (opts.whisper) { info.message = info.message.toLowerCase(); } return info; }); // `volume` is now a function that returns instances of the format. const scream = volume({ yell: true }); console.dir(scream.transform({ level: 'info', message: `sorry for making you YELL in your head!` }, scream.options)); // { // level: 'info' // message: 'SORRY FOR MAKING YOU YELL IN YOUR HEAD!' // } // `volume` can be used multiple times to create different formats. const whisper = volume({ whisper: true }); console.dir(whisper.transform({ level: 'info', message: `WHY ARE THEY MAKING US YELL SO MUCH!` }, whisper.options)); // { // level: 'info' // message: 'why are they making us yell so much!' // } ``` -------------------------------- ### Implement a Custom Winston Transport Source: https://github.com/winstonjs/winston/blob/master/README.md Create a custom transport by extending the 'winston-transport' base class. Implement the 'log' method to define how log messages are processed and sent to a custom destination. ```js const Transport = require('winston-transport'); const util = require('util'); // // Inherit from `winston-transport` so you can take advantage // of the base functionality and `.exceptions.handle()`. // module.exports = class YourCustomTransport extends Transport { constructor(opts) { super(opts); // // Consume any custom options here. e.g.: // - Connection information for databases // - Authentication information for APIs (e.g. loggly, papertrail, // logentries, etc.). // } log(info, callback) { setImmediate(() => { this.emit('logged', info); }); // Perform the writing to the remote service callback(); } }; ``` -------------------------------- ### Defining Custom Logging Levels Source: https://github.com/winstonjs/winston/blob/master/README.md Creates a logger with custom logging levels ('foo', 'bar', 'baz', 'foobar') and associated colors. Logs a message using the custom 'foobar' level. ```js const myCustomLevels = { levels: { foo: 0, bar: 1, baz: 2, foobar: 3 }, colors: { foo: 'blue', bar: 'green', baz: 'yellow', foobar: 'red' } }; const customLevelLogger = winston.createLogger({ levels: myCustomLevels.levels }); customLevelLogger.foobar('some foobar level-ed message'); ``` -------------------------------- ### Enable Rejection Handling on Logger Creation Source: https://github.com/winstonjs/winston/blob/master/README.md Configure winston to catch and log unhandled promise rejections by specifying rejection handlers when creating the logger instance. ```js const { createLogger, transports } = require('winston'); // Enable rejection handling when you create your logger. const logger = createLogger({ transports: [ new transports.File({ filename: 'combined.log' }) ], rejectionHandlers: [ new transports.File({ filename: 'rejections.log' }) ] }); // Or enable it later on by adding a transport or using `.rejections.handle` const logger = createLogger({ transports: [ new transports.File({ filename: 'combined.log' }) ] }); // Call rejections.handle with a transport to handle rejections logger.rejections.handle( new transports.File({ filename: 'rejections.log' }) ); ``` -------------------------------- ### Instantiate Winston Transports Correctly Source: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md Pass an instance of the transport to `logger.add()`, not the transport class itself. This ensures proper initialization and functionality. ```javascript // DON'T DO THIS. It will no longer work logger.add(winston.transports.Console); // Do this instead. logger.add(new winston.transports.Console()); ``` -------------------------------- ### Configure Winston Transports with Custom Options Source: https://github.com/winstonjs/winston/blob/master/README.md Set custom log levels and formats for File, Http, and Console transports when creating a logger instance. This allows granular control over logging behavior for different output destinations. ```js const logger = winston.createLogger({ transports: [ new winston.transports.File({ filename: 'error.log', level: 'error', format: winston.format.json() }), new winston.transports.Http({ level: 'warn', format: winston.format.json() }), new winston.transports.Console({ level: 'info', format: winston.format.combine( winston.format.colorize(), winston.format.simple() ) }) ] }); ``` -------------------------------- ### Handle Rejections with Default Winston Logger Source: https://github.com/winstonjs/winston/blob/master/README.md Add a separate rejection logger to the default winston instance by calling `.rejections.handle()` with a transport, or set `handleRejections` to true when adding transports. ```js // // You can add a separate rejection logger by passing it to `.rejections.handle` // winston.rejections.handle( new winston.transports.File({ filename: 'path/to/rejections.log' }) ); // // Alternatively you can set `handleRejections` to true when adding transports // to winston. // winston.add(new winston.transports.File({ filename: 'path/to/combined.log', handleRejections: true })); ``` -------------------------------- ### Add Mail Transport to Winston Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Sets up the Mail transport for sending logs via email. Requires 'to' and 'host' options. ```javascript const { Mail } = require('winston-mail'); logger.add(new Mail(options)); ``` -------------------------------- ### Initialize VS Code Output Channel Transport Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Set up a Winston logger to output logs to a VS Code Output Channel. This is useful for debugging extensions. ```js 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 })], }); ``` -------------------------------- ### Add Cisco Spark Transport to Winston Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Set up the winston-spark transport to send log messages to a Cisco Spark room. Requires an access token and room ID. ```javascript 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)); ``` -------------------------------- ### Combine Multiple Winston Formats Source: https://github.com/winstonjs/winston/blob/master/README.md Combine several built-in Winston formats into a single format using `format.combine`. This allows for flexible log message structuring, including labels, timestamps, and pretty printing. ```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' } ``` -------------------------------- ### NPM Logging Levels Source: https://github.com/winstonjs/winston/blob/master/README.md Defines the severity ordering and integer priorities for npm logging levels. ```js { error: 0, warn: 1, info: 2, http: 3, verbose: 4, debug: 5, silly: 6 } ``` -------------------------------- ### Reconfigure Winston Logger Source: https://github.com/winstonjs/winston/blob/master/README.md Replaces all existing transports with a new set of transports using the `configure` method. This is useful for wholesale changes to logging destinations and levels. ```js 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) ] }); ``` -------------------------------- ### Handle Logging Completion in Winston v3 Source: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md Use `logger.on('finish', ...)` and `logger.end()` to await all logging messages. The `log` method no longer accepts a callback. ```javascript logger.log('info', 'some message'); logger.on('finish', () => process.exit()); logger.end(); ``` -------------------------------- ### Handle Exceptions with Default Winston Logger Source: https://github.com/winstonjs/winston/blob/master/README.md Configure exception handling for the default Winston logger by calling `winston.exceptions.handle()` with a transport instance. This is a convenient way to add exception logging to a globally available logger. ```js // // You can add a separate exception logger by passing it to `.exceptions.handle` // winston.exceptions.handle( new winston.transports.File({ filename: 'path/to/exceptions.log' }) ); ``` -------------------------------- ### Manage Winston Logger Transports Source: https://github.com/winstonjs/winston/blob/master/README.md Shows how to dynamically manage transports for an existing logger instance. Use `.clear()` to remove all, `.add()` to append, and `.remove()` to detach specific transports. ```js 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 ``` -------------------------------- ### Add Logzio Transport to Winston Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Integrates the Logzio transport for sending logs to Logzio. Requires an API token. ```javascript const winston = require('winston'); const Logzio = require('winston-logzio'); logger.add(new Logzio({ token: '__YOUR_API_TOKEN__' })); ``` -------------------------------- ### Run Winston tests Source: https://github.com/winstonjs/winston/blob/master/README.md Execute various test suites for the Winston library using npm scripts. This includes all tests, unit tests with coverage, integration tests, and TypeScript type verification. ```bash npm test # Runs all tests ``` ```bash npm run test:unit # Runs all Unit tests with coverage ``` ```bash npm run test:integration # Runs all integration tests ``` ```bash npm run test:typescript # Runs tests verifying Typescript types ``` -------------------------------- ### Winlog2 Transport for Windows Event Log Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Integrate Winston with the Windows Event Log using the winlog2 transport. Configure options like event log name and source application. ```javascript const winston = require('winston'); const Winlog2 = require('winston-winlog2'); logger.add(new Winlog2(options)); ``` -------------------------------- ### Enable String Interpolation with splat() Source: https://github.com/winstonjs/winston/blob/master/README.md Enable string interpolation for log messages using `format.splat()`. This format works in conjunction with `util.format` placeholders like `%s` and `%d`. It must be explicitly enabled. ```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 }); ``` -------------------------------- ### Handle Exceptions by Setting handleExceptions on Transport Source: https://github.com/winstonjs/winston/blob/master/README.md Enable exception handling for a specific transport by setting the `handleExceptions` option to `true` when adding the transport to Winston. This integrates exception logging directly into a transport's configuration. ```js // // Alternatively you can set `handleExceptions` to true when adding transports // to winston. // winston.add(new winston.transports.File({ filename: 'path/to/combined.log', handleExceptions: true })); ``` -------------------------------- ### Using the Default Winston Logger Source: https://github.com/winstonjs/winston/blob/master/README.md Access and use the default logger directly from the winston module. Ensure transports are added or removed using `add()` and `remove()` methods, or configured with `configure()`. ```js const winston = require('winston'); winston.log('info', 'Hello distributed log files!'); winston.info('Hello again distributed logs'); winston.level = 'debug'; winston.log('debug', 'Now my debug messages are written to console!'); ``` ```js const files = new winston.transports.File({ filename: 'combined.log' }); const console = new winston.transports.Console(); winston.add(console); winston.add(files); winston.remove(console); ``` ```js winston.configure({ transports: [ new winston.transports.File({ filename: 'somefile.log' }) ] }); ``` -------------------------------- ### Adding Custom Colors to Winston Source: https://github.com/winstonjs/winston/blob/master/README.md Registers custom color mappings with Winston, enabling log formatters like 'colorize' to style output for custom log levels. ```js winston.addColors(myCustomLevels.colors); ``` -------------------------------- ### Add Datadog Transport to Winston Logger Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Configure Winston to send logs to Datadog using the `datadog-logger-integrations` transport. Ensure `ddClientConfig` with `apiKeyAuth` is provided, along with `service`, `ddSource`, and `ddTags` for proper log routing and metadata. ```javascript 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' }) ) ``` -------------------------------- ### Add Cloudant Transport to Winston Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Integrate the winston-cloudant transport to log messages to a Cloudant NoSQL database. Requires connection URL or host/credentials. ```javascript const winston = require('winston'); const WinstonCloudant = require('winston-cloudant'); logger.add(new WinstonCloudant(options)); ``` -------------------------------- ### Enable Exception Handling Later with .exceptions.handle() Source: https://github.com/winstonjs/winston/blob/master/README.md Add exception handling to an existing logger instance by calling the `.exceptions.handle()` method with a transport. This allows dynamic configuration of exception logging. ```js const logger = createLogger({ transports: [ new transports.File({ filename: 'combined.log' }) ] }); // Call exceptions.handle with a transport to handle exceptions logger.exceptions.handle( new transports.File({ filename: 'exceptions.log' }) ); ``` -------------------------------- ### Add SQLite3 Transport to Winston Logger Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Integrate the Winston-SQLite3 transport to log messages to a SQLite database file. Specify the database file path and the parameters to log. ```js const wbs = require('winston-better-sqlite3'); logger.add(new wbs({ // path to the sqlite3 database file on the disk db: '', // A list of params to log params: ['level', 'message'] })); ``` -------------------------------- ### Create Child Winston Loggers Source: https://github.com/winstonjs/winston/blob/master/README.md Generates a child logger from an existing logger, allowing for metadata overrides. Be cautious when extending the `Logger` class as `this` context might be affected. ```js const logger = winston.createLogger({ transports: [ new winston.transports.Console(), ] }); const childLogger = logger.child({ requestId: '451' }); ``` -------------------------------- ### Colorize Full Log Line with JSON Format Source: https://github.com/winstonjs/winston/blob/master/README.md Combine JSON formatting with colorization to apply color to the entire log line. Ensure this format is applied when constructing your logger. ```js winston.format.combine( winston.format.json(), winston.format.colorize({ all: true }) ); ``` -------------------------------- ### Define Winston Logging Levels Source: https://github.com/winstonjs/winston/blob/master/README.md Defines the standard logging levels used by Winston, ordered by severity from most important to least important. ```js const levels = { error: 0, warn: 1, info: 2, http: 3, verbose: 4, debug: 5, silly: 6 }; ``` -------------------------------- ### Add Pusher Transport to Winston Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Integrates the Pusher transport to send logs to a Pusher app for real-time processing. Requires Pusher credentials and configuration for channel and event. ```js const { PusherLogger } = require('winston-pusher'); logger.add(new PusherLogger(options)); ``` -------------------------------- ### Accessing Meta Properties in Winston Info Object Source: https://github.com/winstonjs/winston/blob/master/README.md Demonstrates how to destructure an 'info' object to separate the 'level' and 'message' from other properties, which are considered 'meta'. ```js const { level, message, ...meta } = info; ``` -------------------------------- ### Add Cassandra Transport to Winston Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Configure and add the winston-cassandra transport to log messages to a Cassandra database. Requires cluster connection details and keyspace. ```javascript const Cassandra = require('winston-cassandra').Cassandra; logger.add(new Cassandra(options)); ``` -------------------------------- ### Add Papertrail Transport to Winston Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Integrates the Papertrail transport to send logs to a PapertrailApp log destination over TCP (TLS). ```js const { Papertrail } = require('winston-papertrail'); logger.add(new Papertrail(options)); ``` -------------------------------- ### Configure Slack Incoming Webhook Transport Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Set up the Slack webhook transport for Winston. Provide your Slack incoming webhook URL and optionally configure channel, username, and message formatting. ```js 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'); ``` -------------------------------- ### Awaiting Log Writes with Winston Logger Source: https://github.com/winstonjs/winston/blob/master/README.md Wait for all logs to be written before exiting the process by listening for the 'finish' event on the logger instance after calling `end()`. ```js const transport = new winston.transports.Console(); const logger = winston.createLogger({ transports: [transport] }); logger.on('finish', function (info) { // All `info` log messages has now been logged }); logger.info('CHILL WINSTON!', { seriously: true }); logger.end(); ``` ```js // // Handle errors originating in the logger itself // logger.on('error', function (err) { /* Do Something */ }); ``` -------------------------------- ### Add Seq Transport to Winston Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Integrates the Seq transport to send structured log events to a Seq server. Requires the Seq server URL and optionally an API key. ```js 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) }), })); ``` -------------------------------- ### Add New Relic Agent Transport to Winston Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Integrates the New Relic agent transport for forwarding logs to New Relic, useful when automatic forwarding with ECMAScript modules is not working. ```javascript import winston from 'winston' import NewrelicTransport from 'winston-newrelic-agent-transport' const logger = winston.createLogger() const options = {} logger.add(new NewrelicTransport(options)) ``` -------------------------------- ### Syslog Logging Levels Source: https://github.com/winstonjs/winston/blob/master/README.md Defines the severity ordering and integer priorities for syslog logging levels. ```js { emerg: 0, alert: 1, crit: 2, error: 3, warning: 4, notice: 5, info: 6, debug: 7 } ``` -------------------------------- ### Winston Info Object Structure Source: https://github.com/winstonjs/winston/blob/master/README.md Defines the basic structure of an 'info' object used in Winston logging, including required 'level' and 'message' properties. ```js const info = { level: 'info', // Level of the logging message message: 'Hey! Log something?' // Descriptive message being logged. }; ``` -------------------------------- ### Enable Exception Handling on Logger Creation Source: https://github.com/winstonjs/winston/blob/master/README.md Enable uncaught exception handling by providing exception handlers when creating a logger instance. This ensures that exceptions are logged to a specified file. ```js const { createLogger, transports } = require('winston'); // Enable exception handling when you create your logger. const logger = createLogger({ transports: [ new transports.File({ filename: 'combined.log' }) ], exceptionHandlers: [ new transports.File({ filename: 'exceptions.log' }) ] }); ``` -------------------------------- ### Add Logsene Transport to Winston Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Configures the Logsene transport for sending logs to Logsene via HTTPS. The LOGSENE_TOKEN environment variable is used for authentication. ```javascript const winston = require('winston'); const Logsene = require('winston-logsene'); logger.add(new Logsene({ token: process.env.LOGSENE_TOKEN /* other options */ })); ``` -------------------------------- ### Add Azure Table Transport to Winston Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Integrate the winston-azuretable transport to log messages to Azure Table Storage. Supports Azure Storage Emulator for development. ```javascript const { AzureLogger } = require('winston-azuretable'); logger.add(new AzureLogger(options)); ``` -------------------------------- ### Configure VS Code LogOutputChannelTransport with Custom Levels and Format Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Configure the VS Code LogOutputChannelTransport with custom log levels and formatting. This allows for more structured logging within VS Code extensions. ```js 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 })], }); ``` -------------------------------- ### Add Sentry Transport to Winston Source: https://github.com/winstonjs/winston/blob/master/docs/transports.md Configures the Sentry transport for Winston, sending logs and errors to Sentry.io. A Sentry DSN is required. ```js const Sentry = require('winston-transport-sentry-node').default; logger.add(new Sentry({ sentry: { dsn: 'https://******@sentry.io/12345', }, level: 'info' })); ```