Gathering detailed insights and metrics for express-winston
Gathering detailed insights and metrics for express-winston
Gathering detailed insights and metrics for express-winston
Gathering detailed insights and metrics for express-winston
npm install express-winston
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
799 Stars
308 Commits
187 Forks
17 Watching
6 Branches
63 Contributors
Updated on 23 Nov 2024
JavaScript (95.51%)
TypeScript (4.49%)
Cumulative downloads
Total Downloads
Last day
-5.3%
72,522
Compared to previous day
Last week
-3.4%
400,326
Compared to previous week
Last month
2.3%
1,751,838
Compared to previous month
Last year
8.5%
17,923,228
Compared to previous year
1
winston middleware for express.js
npm install winston express-winston
(supports node >= 6)
The maintainers of this project no longer feel comfortable with the following terms:
Therefore, exposed configuration options, types in this library using those terms are due to be removed in the upcoming 5.x series,
including the master branch, you should update your apps and your code accordingly.
We've taken immediate action to make main
our default branch in Git.
You can track the progress of these changes in #247.
express-winston provides middlewares for request and error logging of your express.js application. It uses 'whitelists' to select properties from the request and (new in 0.2.x) response objects.
To make use of express-winston, you need to add the following to your application:
In package.json
:
{
"dependencies": {
"...": "...",
"winston": "^3.0.0",
"express-winston": "^4.0.4",
"...": "..."
}
}
In server.js
(or wherever you need it):
var winston = require('winston'),
expressWinston = require('express-winston');
Use expressWinston.logger(options)
to create a middleware to log your HTTP requests.
1 var router = require('./my-express-router'); 2 3 app.use(expressWinston.logger({ 4 transports: [ 5 new winston.transports.Console() 6 ], 7 format: winston.format.combine( 8 winston.format.colorize(), 9 winston.format.json() 10 ), 11 meta: true, // optional: control whether you want to log the meta data about the request (default to true) 12 msg: "HTTP {{req.method}} {{req.url}}", // optional: customize the default logging message. E.g. "{{res.statusCode}} {{req.method}} {{res.responseTime}}ms {{req.url}}" 13 expressFormat: true, // Use the default Express/morgan request formatting. Enabling this will override any msg if true. Will only output colors with colorize set to true 14 colorize: false, // Color the text and status code, using the Express/morgan color palette (text: gray, status: default green, 3XX cyan, 4XX yellow, 5XX red). 15 ignoreRoute: function (req, res) { return false; } // optional: allows to skip some log messages based on request and/or response 16 })); 17 18 app.use(router); // notice how the router goes after the logger.
1 transports: [<WinstonTransport>], // list of all winston transports instances to use. 2 format: [<logform.Format>], // formatting desired for log output. 3 winstonInstance: <WinstonLogger>, // a winston logger instance. If this is provided the transports and formats options are ignored. 4 level: String or function(req, res) { return String; }, // log level to use, the default is "info". Assign a function to dynamically set the level based on request and response, or a string to statically set it always at that level. statusLevels must be false for this setting to be used. 5 msg: String or function, // customize the default logging message. E.g. "{{res.statusCode}} {{req.method}} {{res.responseTime}}ms {{req.url}}", "HTTP {{req.method}} {{req.url}}" or function(req, res) { return `${res.statusCode} - ${req.method}` }, // Warning: while supported, returning mustache style interpolation from an options.msg function has performance and memory implications under load. 6 expressFormat: Boolean, // Use the default Express/morgan request formatting. Enabling this will override any msg if true. Will only output colors when colorize set to true 7 colorize: Boolean, // Color the text and status code, using the Express/morgan color palette (text: gray, status: default green, 3XX cyan, 4XX yellow, 5XX red). 8 meta: Boolean, // control whether you want to log the meta data about the request (default to true). 9 baseMeta: Object, // default meta data to be added to log, this will be merged with the meta data. 10 metaField: String, // if defined, the meta data will be added in this field instead of the meta root object. Defaults to 'meta'. Set to `null` to store metadata at the root of the log entry. 11 requestField: [String] // the property of the metadata to store the request under (default 'req'). Set to null to exclude request from metadata 12 statusLevels: Boolean or Object, // different HTTP status codes caused log messages to be logged at different levels (info/warn/error), the default is false. Use an object to control the levels various status codes are logged at. Using an object for statusLevels overrides any setting of options.level. 13 ignoreRoute: function (req, res) { return false; }, // A function to determine if logging is skipped, defaults to returning false. Called _before_ any later middleware. 14 skip: function(req, res) { return false; }, // A function to determine if logging is skipped, defaults to returning false. Called _after_ response has already been sent. 15 requestFilter: function (req, propName) { return req[propName]; }, // A function to filter/return request values, defaults to returning all values allowed by whitelist. If the function returns undefined, the key/value will not be included in the meta. 16 responseFilter: function (res, propName) { return res[propName]; }, // A function to filter/return response values, defaults to returning all values allowed by whitelist. If the function returns undefined, the key/value will not be included in the meta. 17 requestWhitelist: [String], // Array of request properties to log. Overrides global requestWhitelist for this instance 18 responseWhitelist: [String], // Array of response properties to log. Overrides global responseWhitelist for this instance 19 bodyWhitelist: [String], // Array of body properties to log. Overrides global bodyWhitelist for this instance 20 bodyBlacklist: [String], // Array of body properties to omit from logs. Overrides global bodyBlacklist for this instance 21 ignoredRoutes: [String], // Array of paths to ignore/skip logging. Overrides global ignoredRoutes for this instance 22 dynamicMeta: function(req, res) { return [Object]; } // Extract additional meta data from request or response (typically req.user data if using passport). meta must be true for this function to be activated 23 headerBlacklist: [String], // Array of headers to omit from logs. Applied after any previous filters. 24
Use expressWinston.errorLogger(options)
to create a middleware that log the errors of the pipeline.
1 var router = require('./my-express-router'); 2 3 app.use(router); // notice how the router goes first. 4 app.use(expressWinston.errorLogger({ 5 transports: [ new winston.transports.Console() ], 6 format: winston.format.combine( 7 winston.format.colorize(), 8 winston.format.json() 9 ) 10 }));
The logger needs to be added AFTER the express router (app.router
) and BEFORE any of your custom error handlers (express.handler
). Since express-winston will just log the errors and not handle them, you can still use your custom error handler like express.handler
, just be sure to put the logger before any of your handlers.
1 transports: [<WinstonTransport>], // list of all winston transports instances to use. 2 format: [<logform.Format>], // formatting desired for log output 3 winstonInstance: <WinstonLogger>, // a winston logger instance. If this is provided the transports and formats options are ignored. 4 msg: String or function // customize the default logging message. E.g. "{{err.message}} {{res.statusCode}} {{req.method}}" or function(req, res) { return `${res.statusCode} - ${req.method}` } 5 baseMeta: Object, // default meta data to be added to log, this will be merged with the error data. 6 meta: Boolean, // control whether you want to log the meta data about the request (default to true). 7 metaField: String, // if defined, the meta data will be added in this field instead of the meta root object. Defaults to 'meta'. Set to `null` to store metadata at the root of the log entry. 8 requestField: [String] // the property of the metadata to store the request under (default 'req'). Set to null to exclude request from metadata 9 responseField: [String] // the property of the metadata to store the response under (default 'res'). If set to the same as 'requestField', filtered response and request properties will be merged. Set to null to exclude request from metadata 10 requestFilter: function (req, propName) { return req[propName]; } // A function to filter/return request values, defaults to returning all values allowed by whitelist. If the function returns undefined, the key/value will not be included in the meta. 11 requestWhitelist: [String] // Array of request properties to log. Overrides global requestWhitelist for this instance 12 headerBlacklist: [String], // Array of headers to omit from logs. Applied after any previous filters. 13 level: String or function(req, res, err) { return String; }// custom log level for errors (default is 'error'). Assign a function to dynamically set the log level based on request, response, and the exact error. 14 dynamicMeta: function(req, res, err) { return [Object]; } // Extract additional meta data from request or response (typically req.user data if using passport). meta must be true for this function to be activated 15 exceptionToMeta: function(error){return Object; } // Function to format the returned meta information on error log. If not given `winston.exception.getAllInfo` will be used by default 16 blacklistedMetaFields: [String] // fields to blacklist from meta data 17 skip: function(req, res, err) { return false; } // A function to determine if logging is skipped, defaults to returning false.
To use winston's existing transports, set transports
to the values (as in key-value) of the winston.default.transports
object. This may be done, for example, by using underscorejs: transports: _.values(winston.default.transports)
.
Alternatively, if you're using a winston logger instance elsewhere and have already set up levels and transports, pass the instance into expressWinston with the winstonInstance
option. The transports
option is then ignored.
metaField
optionIn versions of express-winston
prior to 4.0.0, this field functioned differently.
Previously the log entry would always have a "meta" field which would be set to the metadata of the request/error.
If metaField
was set, this information would be stored as an object with the given property on the "meta" object of
the log entry. This prevented the use case where the metadata should be located at the root of the log entry.
In this version, metaField
defaults to "meta" which maintains the prior versions behavior of storing the metadata at
a "meta" property of the log entry.
Explicitly setting the metaField
to null
or "null" causes the metadata to be stored at the root of the log entry.
The metaField
option now also supports dot separated and array values to store the metadata at a nested location in the log entry.
1 var express = require('express'); 2 var expressWinston = require('express-winston'); 3 var winston = require('winston'); // for transports.Console 4 var app = module.exports = express(); 5 6 app.use(express.bodyParser()); 7 app.use(express.methodOverride()); 8 9 // Let's make our express `Router` first. 10 var router = express.Router(); 11 router.get('/error', function(req, res, next) { 12 // here we cause an error in the pipeline so we see express-winston in action. 13 return next(new Error("This is an error and it should be logged to the console")); 14 }); 15 16 router.get('/', function(req, res, next) { 17 res.write('This is a normal request, it should be logged to the console too'); 18 res.end(); 19 }); 20 21 // express-winston logger makes sense BEFORE the router 22 app.use(expressWinston.logger({ 23 transports: [ new winston.transports.Console() ], 24 format: winston.format.combine( 25 winston.format.colorize(), 26 winston.format.json() 27 ) 28 })); 29 30 // Now we can tell the app to use our routing code: 31 app.use(router); 32 33 // express-winston errorLogger makes sense AFTER the router. 34 app.use(expressWinston.errorLogger({ 35 transports: [ new winston.transports.Console() ], 36 format: winston.format.combine( 37 winston.format.colorize(), 38 winston.format.json() 39 ) 40 })); 41 42 // Optionally you can include your custom error handler after the logging. 43 app.use(express.errorLogger({ 44 dumpExceptions: true, 45 showStack: true 46 })); 47 48 app.listen(3000, function(){ 49 console.log("express-winston demo listening on port %d in %s mode", this.address().port, app.settings.env); 50 });
Browse /
to see a regular HTTP logging like this:
{
"req": {
"httpVersion": "1.1",
"headers": {
"host": "localhost:3000",
"connection": "keep-alive",
"accept": "*/*",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11",
"accept-encoding": "gzip,deflate,sdch",
"accept-language": "en-US,en;q=0.8,es-419;q=0.6,es;q=0.4",
"accept-charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
"cookie": "connect.sid=nGspCCSzH1qxwNTWYAoexI23.seE%2B6Whmcwd"
},
"url": "/",
"method": "GET",
"originalUrl": "/",
"query": {}
},
"res": {
"statusCode": 200
},
"responseTime" : 12,
"level": "info",
"message": "HTTP GET /favicon.ico"
}
Browse /error
will show you how express-winston handles and logs the errors in the express pipeline like this:
{
"date": "Thu Jul 19 2012 23:39:44 GMT-0500 (COT)",
"process": {
"pid": 35719,
"uid": 501,
"gid": 20,
"cwd": "/Users/thepumpkin/Projects/testExpressWinston",
"execPath": "/usr/local/bin/node",
"version": "v0.6.18",
"argv": [
"node",
"/Users/thepumpkin/Projects/testExpressWinston/app.js"
],
"memoryUsage": {
"rss": 14749696,
"heapTotal": 7033664,
"heapUsed": 5213280
}
},
"os": {
"loadavg": [
1.95068359375,
1.5166015625,
1.38671875
],
"uptime": 498086
},
"trace": [
...,
{
"column": 3,
"file": "Object].log (/Users/thepumpkin/Projects/testExpressWinston/node_modules/winston/lib/winston/transports/console.js",
"function": "[object",
"line": 87,
"method": null,
"native": false
}
],
"stack": [
"Error: This is an error and it should be logged to the console",
" at /Users/thepumpkin/Projects/testExpressWinston/app.js:39:15",
" at callbacks (/Users/thepumpkin/Projects/testExpressWinston/node_modules/express/lib/router/index.js:272:11)",
" at param (/Users/thepumpkin/Projects/testExpressWinston/node_modules/express/lib/router/index.js:246:11)",
" at pass (/Users/thepumpkin/Projects/testExpressWinston/node_modules/express/lib/router/index.js:253:5)",
" at Router._dispatch (/Users/thepumpkin/Projects/testExpressWinston/node_modules/express/lib/router/index.js:280:4)",
" at Object.handle (/Users/thepumpkin/Projects/testExpressWinston/node_modules/express/lib/router/index.js:45:10)",
" at next (/Users/thepumpkin/Projects/testExpressWinston/node_modules/express/node_modules/connect/lib/http.js:204:15)",
" at done (/Users/thepumpkin/Dropbox/Projects/express-winston/index.js:91:14)",
" at /Users/thepumpkin/Dropbox/Projects/express-winston/node_modules/async/lib/async.js:94:25",
" at [object Object].log (/Users/thepumpkin/Projects/testExpressWinston/node_modules/winston/lib/winston/transports/console.js:87:3)"
],
"req": {
"httpVersion": "1.1",
"headers": {
"host": "localhost:3000",
"connection": "keep-alive",
"cache-control": "max-age=0",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11",
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"accept-encoding": "gzip,deflate,sdch",
"accept-language": "en-US,en;q=0.8,es-419;q=0.6,es;q=0.4",
"accept-charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
"cookie": "connect.sid=nGspCCSzH1qxwNTWYAoexI23.seE%2B6WhmcwdzFEjqhMDuIIl3mAUY7dT4vn%2BkWvRPhZc"
},
"url": "/error",
"method": "GET",
"originalUrl": "/error",
"query": {}
},
"level": "error",
"message": "middlewareError"
}
If using this library with @google-cloud/logging-winston
, use the following configuration to properly store httpRequest information.
See https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry
1var express = require('express'); 2var expressWinston = require('express-winston'); 3var LoggingWinston = require('@google-cloud/logging-winston').LoggingWinston; 4 5const app = express() 6 7app.use(expressWinston.logger({ 8 transports: [new LoggingWinston({})], 9 metaField: null, //this causes the metadata to be stored at the root of the log entry 10 responseField: null, // this prevents the response from being included in the metadata (including body and status code) 11 requestWhitelist: ['headers', 'query'], //these are not included in the standard StackDriver httpRequest 12 responseWhitelist: ['body'], // this populates the `res.body` so we can get the response size (not required) 13 dynamicMeta: (req, res) => { 14 const httpRequest = {} 15 const meta = {} 16 if (req) { 17 meta.httpRequest = httpRequest 18 httpRequest.requestMethod = req.method 19 httpRequest.requestUrl = `${req.protocol}://${req.get('host')}${req.originalUrl}` 20 httpRequest.protocol = `HTTP/${req.httpVersion}` 21 // httpRequest.remoteIp = req.ip // this includes both ipv6 and ipv4 addresses separated by ':' 22 httpRequest.remoteIp = req.ip.indexOf(':') >= 0 ? req.ip.substring(req.ip.lastIndexOf(':') + 1) : req.ip // just ipv4 23 httpRequest.requestSize = req.socket.bytesRead 24 httpRequest.userAgent = req.get('User-Agent') 25 httpRequest.referrer = req.get('Referrer') 26 } 27 28 if (res) { 29 meta.httpRequest = httpRequest 30 httpRequest.status = res.statusCode 31 httpRequest.latency = { 32 seconds: Math.floor(res.responseTime / 1000), 33 nanos: ( res.responseTime % 1000 ) * 1000000 34 } 35 if (res.body) { 36 if (typeof res.body === 'object') { 37 httpRequest.responseSize = JSON.stringify(res.body).length 38 } else if (typeof res.body === 'string') { 39 httpRequest.responseSize = res.body.length 40 } 41 } 42 } 43 return meta 44 } 45}));
Express-winston exposes three whitelists that control which properties of the request
, body
, and response
are logged:
requestWhitelist
bodyWhitelist
, bodyBlacklist
responseWhitelist
For example, requestWhitelist
defaults to:
['url', 'headers', 'method', 'httpVersion', 'originalUrl', 'query'];
Only those properties of the request object will be logged. Set or modify the whitelist as necessary.
For example, to include the session property (the session data), add the following during logger setup:
expressWinston.requestWhitelist.push('session');
The blacklisting excludes certain properties and keeps all others. If both bodyWhitelist
and bodyBlacklist
are set
the properties excluded by the blacklist are not included even if they are listed in the whitelist!
Example:
expressWinston.bodyBlacklist.push('secretid', 'secretproperty');
Note that you can log the whole request and/or response body:
expressWinston.requestWhitelist.push('body');
expressWinston.responseWhitelist.push('body');
requestWhitelist
and responseWhitelist
also support nested whitelist values, allowing access to parts of an object.
For example, using the following during logger setup:
expressWinston.responseWhitelist.push('body.important.value');
A response that looks like this :
{
body: {
important: {
value: 5
},
notImportant: {
value: 7
}
},
other: {
value: 3
}
}
Would only log the following value :
{
body: {
important: {
value: 5
}
}
}
New in version 0.2.x is the ability to add whitelist elements in a route. express-winston adds a _routeWhitelists
object to the req
uest, containing .body
, .req
and .res
properties, to which you can set an array of 'whitelist' parameters to include in the log, specific to the route in question:
1 router.post('/user/register', function(req, res, next) { 2 req._routeWhitelists.body = ['username', 'email', 'age']; // But not 'password' or 'confirm-password' or 'top-secret' 3 req._routeWhitelists.res = ['_headers']; 4 });
Post to /user/register
would give you something like the following:
{
"req": {
"httpVersion": "1.1",
"headers": {
"host": "localhost:3000",
"connection": "keep-alive",
"accept": "*/*",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11",
"accept-encoding": "gzip,deflate,sdch",
"accept-language": "en-US,en;q=0.8,es-419;q=0.6,es;q=0.4",
"accept-charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
"cookie": "connect.sid=nGspCCSzH1qxwNTWYAoexI23.seE%2B6Whmcwd"
},
"url": "/",
"method": "GET",
"originalUrl": "/",
"query": {},
"body": {
"username": "foo",
"email": "foo@bar.com",
"age": "72"
}
},
"res": {
"statusCode": 200
},
"responseTime" : 12,
"level": "info",
"message": "HTTP GET /favicon.ico"
}
Blacklisting supports only the body
property.
1 router.post('/user/register', function(req, res, next) { 2 req._routeWhitelists.body = ['username', 'email', 'age']; // But not 'password' or 'confirm-password' or 'top-secret' 3 req._routeBlacklists.body = ['username', 'password', 'confirm-password', 'top-secret']; 4 req._routeWhitelists.res = ['_headers']; 5 });
If both req._routeWhitelists.body
and req._routeBlacklists.body
are set the result will be the white listed properties
excluding any black listed ones. In the above example, only 'email' and 'age' would be included.
If you set statusLevels
to true
express-winston will log sub 400 responses at info level, sub 500 responses as warnings and 500+ responses as errors. To change these levels specify an object as follows
1 "statusLevels": { 2 "success": "debug", 3 "warn": "debug", 4 "error": "info" 5 }
If you set statusLevels
to false
and assign a function to level, you can customize the log level for any scenario.
1 statusLevels: false // default value 2 level: function (req, res) { 3 var level = ""; 4 if (res.statusCode >= 100) { level = "info"; } 5 if (res.statusCode >= 400) { level = "warn"; } 6 if (res.statusCode >= 500) { level = "error"; } 7 // Ops is worried about hacking attempts so make Unauthorized and Forbidden critical 8 if (res.statusCode == 401 || res.statusCode == 403) { level = "critical"; } 9 // No one should be using the old path, so always warn for those 10 if (req.path === "/v1" && level === "info") { level = "warn"; } 11 return level; 12 }
If you set dynamicMeta
function you can extract additional meta data fields from request or response objects.
The function can be used to either select relevant elements in request or response body without logging them as a whole
or to extract runtime data like the user making the request. The example below logs the user name and role as assigned
by the passport authentication middleware.
1 meta: true, 2 dynamicMeta: function(req, res) { 3 return { 4 user: req.user ? req.user.username : null, 5 role: req.user ? req.user.role : null, 6 ... 7 } 8}
Run the basic Mocha tests:
npm test
View the coverage report:
npx http-server coverage/lcov-report
If you ran into any problems, please use the project Issues section to search or post any bug.
Also see AUTHORS file, add yourself if you are missing.
Copyright (c) 2012 Bithavoc.io and Contributors - http://bithavoc.io
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
Found 11/20 approved changesets -- score normalized to 5
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More