winston
Описание
форк https://github.com/winstonjs/winston
Языки
- JavaScript99,2%
- TypeScript0,8%
winston
A logger for just about everything.
winston@3
See the Upgrade Guide for more information. Bug reports and PRs welcome!
Looking for winston@2.x documentation?
Please note that the documentation below is for .
Read the documentation.
Motivation
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 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.
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 in .
There are a number of other examples in .
Don't see an example you think should be there? Submit a pull request
to add it!
Usage
The recommended way to use is to create your own logger. The
simplest way to do this is using :
You may also log directly via the default logger exposed by
, 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
- Formats
- Logging levels
- Transports
- Exceptions
- Rejections
- Profiling
- Streaming Logs
- Querying Logs
- Further Reading
- Installation
- Run Tests
Logging
Logging levels in conform to the severity ordering specified by
RFC5424: severity of all levels is assumed to be numerically ascending
from most important to least important.
Creating your own Logger
You get started by creating a logger using :
A logger accepts the following parameters:
| Name | Default | Description |
|---|---|---|
| | Log only if is less than or equal to this level |
| | Levels (and colors) representing log priorities |
| | Formatting for messages (see: Formats) |
| (No transports) | Set of logging targets for messages |
| | If false, handled exceptions will not cause |
| | If true, all logs are suppressed |
The levels provided to will be defined as convenience methods
on the returned.
You can add or remove transports from the once it has been provided
to you from :
You can also wholesale reconfigure a instance using the
method:
Creating child loggers
You can create child loggers from existing loggers to pass metadata overrides:
is likely to be bugged if you're also extending the.childclass, due to some implementation details that makeLoggerkeyword to point to unexpected things. Use with caution.this
Streams, objectMode, and info objects
In , both and instances are treated as
streams that accept an object.
The parameter provided to a given format represents a single log
message. The object itself is mutable. Every must have at least the
and properties:
Properties besides level and message are considered as "". i.e.:
Several of the formats in itself add additional properties:
| Property | Format added by | Description |
|---|---|---|
| | String interpolation splat for -style messages. |
| | timestamp the message was received. |
| | Custom label associated with each message. |
| | Number of milliseconds since the previous log message. |
As a consumer you may add whatever properties you wish – internal state is
maintained by properties:
(READ-ONLY): equal toSymbol.for('level')property. Is treated as immutable by all code.levelcomplete string message set by "finalizing formats":Symbol.for('message'):- json
- logstash
- printf
- prettyPrint
- simple
: additional string interpolation arguments. Used exclusively bySymbol.for('splat')format.splat()
These Symbols are stored in another package: so that all
consumers of can have the same Symbol reference. i.e.:
NOTE: any
property in a{ message }object provided will automatically be concatenated to anymetaalready provided: For example the below will concatenate 'world' onto 'hello':msg
Formats
Formats in can be accessed from . They are
implemented in , a separate
module from . This allows flexibility when writing your own transports
in case you wish to include a default format with your transport.
In modern versions of template strings are very performant and are the
recommended way for doing most end-user formatting. If you want to bespoke
format your logs, is for you:
To see what built-in formats are available and learn more about creating your
own custom logging formats, see .
Combining formats
Any number of formats may be combined into a single format using
. Since takes no , as a convenience it
returns pre-created instance of the combined format.
String interpolation
The method provides the string interpolation using util.format. It
must be enabled using .
Below is an example that defines a format with string interpolation of
messages using and then serializes the entire message
using .
Filtering info Objects
If you wish to filter out a given Object completely when logging then
simply return a falsey value.
Use of will respect any falsey values return and stop
evaluation of later formats in the series. For example:
Creating custom formats
Formats are prototypal objects (i.e. class instances) that define a single
method: and return the mutated :
: an object representing the log message.info: setting specific to the current instance of the format.opts
They are expected to return one of two things:
- An
Object representing the modifiedinfoargument. Object references need not be preserved if immutability is preferred. All current built-in formats considerinfomutable, but [immutablejs] is being considered for future releases.info - A falsey value indicating that the
argument should be ignored by the caller. (See: FilteringinfoObjects) below.info
is designed to be as simple as possible. To define a new
format, simply pass it a function to get a new
.
The named returned can be used to create as many copies of the given
as desired:
Logging Levels
Logging levels in conform to the severity ordering specified by
RFC5424: severity of all levels is assumed to be numerically ascending
from most important to least important.
Each is given a specific integer priority. The higher the priority the
more important the message is considered to be, and the lower the
corresponding integer priority. For example, as specified exactly in RFC5424
the levels are prioritized from 0 to 7 (highest to lowest).
Similarly, logging levels are prioritized from 0 to 6 (highest to
lowest):
If you do not explicitly define the levels that should use, the
levels above will be used.
Using Logging Levels
Setting the level for your logging message can be accomplished in one of two ways. You can pass a string representing the logging level to the log() method or use the level specified methods defined on every winston Logger.
allows you to define a property on each transport which
specifies the maximum level of messages that a transport should log. For
example, using the levels you could log only messages to the
console and everything and below to a file (which includes
messages):
You may also dynamically change the log level of a transport:
supports customizable logging levels, defaulting to npm style
logging levels. Levels must be specified at the time of creating your logger.
Using Custom Logging Levels
In addition to the predefined , , and levels available in
, you can also choose to define your own:
Although there is slight repetition in this data structure, it enables simple encapsulation if you do not want to have colors. If you do wish to have colors, in addition to passing the levels to the Logger itself, you must make winston aware of them:
This enables loggers using the formatter to appropriately color and style
the output of custom levels.
Additionally, you can also change background color and font style. For example,
Possible options are below.
-
Font styles:
,bold,dim,italic,underline,inverse,hidden.strikethrough -
Font foreground colors:
,black,red,green,yellow,blue,magenta,cyan,white,gray.grey -
Background colors:
,blackBG,redBG,greenBG,yellowBGblueBG,magentaBG,cyanBGwhiteBG
Colorizing Standard logging levels
To colorize the standard logging level add
where is whatever other formatter you want to use. The formatter must come before any formatters adding text you wish to color.
Colorizing full log line when json formatting logs
To colorize the full log line with the json formatter you can apply the following
Transports
There are several core transports included in , which leverage the
built-in networking and file I/O offered by Node.js core. In addition, there
are additional transports written by members of the community.
Multiple transports of the same type
It is possible to use multiple transports of the same type e.g.
when you construct the transport.
If you later want to remove one of these transports you can do so by using the transport itself. e.g.:
Adding Custom Transports
Adding a custom transport is easy. All you need to do is accept any options
you need, implement a log() method, and consume it with .
Common Transport options
As every transport inherits from winston-transport, it's possible to set a custom format and a custom log level on each transport separately:
Exceptions
Handling Uncaught Exceptions with winston
With , it is possible to catch and log events
from your process. With your own logger instance you can enable this behavior
when it's created or later on in your applications lifecycle:
If you want to use this feature with the default logger, simply call
with a transport instance.
To Exit or Not to Exit
By default, winston will exit after logging an uncaughtException. If this is
not the behavior you want, set
When working with custom logger instances, you can pass in separate transports
to the property or set on any
transport.
Example 1
Example 2
The option can also be a function to prevent exit on only
certain types of errors:
Rejections
Handling Uncaught Promise Rejections with winston
With , it is possible to catch and log events
from your process. With your own logger instance you can enable this behavior
when it's created or later on in your applications lifecycle:
If you want to use this feature with the default logger, simply call
with a transport instance.
Profiling
In addition to logging messages and metadata, also has a simple
profiling mechanism implemented for any logger:
Also you can start a timer and keep a reference that you can call
on:
All profile messages are set to 'info' level by default, and both message and
metadata are optional. For individual profile messages, you can override the default log level by supplying a metadata object with a property:
Querying Logs
supports querying of logs with Loggly-like options. See Loggly
Search API. Specifically:
, , , , , and .
Streaming Logs
Streaming allows you to stream your logs back from your chosen transport.
Further Reading
Using the Default Logger
The default logger is accessible through the module directly. Any
method that you could call on an instance of a logger is available on the
default logger:
By default, no transports are set on the default logger. You must
add or remove transports via the and methods:
Or do it with one call to configure():
For more documentation about working with each individual transport supported
by see the Transports document.
Awaiting logs to be written in winston
Often it is useful to wait for your logs to be written before exiting the
process. Each instance of is also a [Node.js stream]. A
event will be raised when all logs have flushed to all transports
after the stream has been ended.
It is also worth mentioning that the logger also emits an 'error' event if an error occurs within the logger itself which you should handle or suppress if you don't want unhandled exceptions:
Working with multiple Loggers in winston
Often in larger, more complex, applications it is necessary to have multiple
logger instances with different settings. Each logger is responsible for a
different feature area (or category). This is exposed in in two
ways: through and instances of . In fact,
is just a predefined instance of :
Now that your loggers are setup, you can require winston in any file in your application and access these pre-configured loggers:
If you prefer to manage the yourself, you can simply instantiate one:
Routing Console transport messages to the console instead of stdout and stderr
By default the transport sends messages to and . This
is fine in most situations; however, there are some cases where this isn't desirable, including:
- Debugging using VSCode and attaching to, rather than launching, a Node.js process
- Writing JSON format messages in AWS Lambda
- Logging during Jest tests with the
option--silent
To make the transport log use , and
instead, set the option to :
Installation
Run Tests
All of the winston tests are written with , , and
. They can be run with .
