winston-middleware 3.0.1 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of winston-middleware might be problematic. Click here for more details.

package/AUTHORS CHANGED
@@ -7,3 +7,6 @@ Damian Kaczmarek <rush@rushbase.net>
7
7
  Robbie Trencheny <me@robbiet.us> (http://robbie.io)
8
8
  Ross Brandes <ross.brandes@gmail.com>
9
9
  Kévin Maschtaler (https://www.kmaschta.me)
10
+ Matthew Blasius <matthew.blasius@expel.io> (https://expel.io)
11
+ Maxime David <contact@maximedavid.fr>
12
+ Matt Morrissette <yinzara@gmail.com> (https://github.com/yinzara)
package/CHANGELOG.md CHANGED
@@ -1,3 +1,32 @@
1
+ ## 4.0.1
2
+ * Added `headerBlacklist` to BaseLoggerOptions for better typescript support ([#228](https://github.com/bithavoc/winston-middleware/pull/228))
3
+
4
+ ## 4.0.0
5
+ * Changed `metaField` configuration property functionality (see Readme.md) ([#209](https://github.com/bithavoc/winston-middleware/issues/209)) - BREAKING CHANGE
6
+ * Moved type definitions to be embedded inside library ([#123](https://github.com/bithavoc/winston-middleware/issues/123))
7
+ * Added "files" to package.json to reduce unnecessary files in released package
8
+ * Added StackDriver/Google Cloud Logging specific instructions to Readme.md
9
+ * Added `requestField` and `responseField` options to allow storing the request and response in different metadata fields (or not at all)
10
+ * Fixed `meta` configuration option on `errorLogger` (was not functioning at all)
11
+ * Added .editorconfig and reformatted library to match
12
+
13
+ ## 3.4.0
14
+ * Added: Nested Whitelists ([#225](https://github.com/bithavoc/winston-middleware/pull/225), @kapalex)
15
+
16
+ ## 3.3.0
17
+ * Added: options.headerBlacklist ([#217](https://github.com/bithavoc/winston-middleware/pull/217), @maxday)
18
+
19
+ ## 3.2.1
20
+ * Added: options.skip ([#214](https://github.com/bithavoc/winston-middleware/pull/214), [#147](https://github.com/bithavoc/winston-middleware/pull/147), @ahnkee)
21
+
22
+ ## 3.2.0
23
+ * Replaced: _header -> getHeader ([#210](https://github.com/bithavoc/winston-middleware/pull/210), @Gregoirevda)
24
+ * Replaced coverage tool blanket with nyc ([#211](https://github.com/bithavoc/winston-middleware/pull/211), @golopot)
25
+ * Add eslint and fix lint errors ([#212](https://github.com/bithavoc/winston-middleware/pull/212), @golopot)
26
+
27
+ ## 3.1.0
28
+ * Fix large _.template memory consumption ([#203](https://github.com/bithavoc/winston-middleware/pull/203), @slickmb)
29
+
1
30
  ## 3.0.1
2
31
  * Add `format` to `options` to allow user-specified formatting following winston@3 conventions ([#190](https://github.com/bithavoc/winston-middleware/pull/190), @crellison)
3
32
 
package/LICENSE CHANGED
@@ -1,4 +1,4 @@
1
- Copyright (c) 2012-2014 Bithavoc.io - http://bithavoc.io
1
+ Copyright (c) 2012 Bithavoc.io - http://bithavoc.io
2
2
 
3
3
  Permission is hereby granted, free of charge, to any person obtaining a copy
4
4
  of this software and associated documentation files (the "Software"), to deal
package/Readme.md CHANGED
@@ -51,9 +51,9 @@ Use `expressWinston.logger(options)` to create a middleware to log your HTTP req
51
51
  new winston.transports.Console()
52
52
  ],
53
53
  format: winston.format.combine(
54
- winston.format.colorize()
54
+ winston.format.colorize(),
55
55
  winston.format.json()
56
- )
56
+ ),
57
57
  meta: true, // optional: control whether you want to log the meta data about the request (default to true)
58
58
  msg: "HTTP {{req.method}} {{req.url}}", // optional: customize the default logging message. E.g. "{{res.statusCode}} {{req.method}} {{res.responseTime}}ms {{req.url}}"
59
59
  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
@@ -71,23 +71,25 @@ Use `expressWinston.logger(options)` to create a middleware to log your HTTP req
71
71
  format: [<logform.Format>], // formatting desired for log output.
72
72
  winstonInstance: <WinstonLogger>, // a winston logger instance. If this is provided the transports and formats options are ignored.
73
73
  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.
74
- 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}` }
74
+ 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.
75
75
  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
76
76
  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).
77
77
  meta: Boolean, // control whether you want to log the meta data about the request (default to true).
78
78
  baseMeta: Object, // default meta data to be added to log, this will be merged with the meta data.
79
- metaField: String, // if defined, the meta data will be added in this field instead of the meta root object.
80
- 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.
81
- ignoreRoute: function (req, res) { return false; } // A function to determine if logging is skipped, defaults to returning false. Called _before_ any later middleware.
82
- 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.
83
- 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.
84
- 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.
85
- requestWhitelist: [String] // Array of request properties to log. Overrides global requestWhitelist for this instance
86
- responseWhitelist: [String] // Array of response properties to log. Overrides global responseWhitelist for this instance
87
- bodyWhitelist: [String] // Array of body properties to log. Overrides global bodyWhitelist for this instance
88
- bodyBlacklist: [String] // Array of body properties to omit from logs. Overrides global bodyBlacklist for this instance
89
- ignoredRoutes: [String] // Array of paths to ignore/skip logging. Overrides global ignoredRoutes for this instance
79
+ 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.
80
+ requestField: [String] // the property of the metadata to store the request under (default 'req'). Set to null to exclude request from metadata
81
+ 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.
82
+ ignoreRoute: function (req, res) { return false; }, // A function to determine if logging is skipped, defaults to returning false. Called _before_ any later middleware.
83
+ 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.
84
+ 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.
85
+ 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.
86
+ requestWhitelist: [String], // Array of request properties to log. Overrides global requestWhitelist for this instance
87
+ responseWhitelist: [String], // Array of response properties to log. Overrides global responseWhitelist for this instance
88
+ bodyWhitelist: [String], // Array of body properties to log. Overrides global bodyWhitelist for this instance
89
+ bodyBlacklist: [String], // Array of body properties to omit from logs. Overrides global bodyBlacklist for this instance
90
+ ignoredRoutes: [String], // Array of paths to ignore/skip logging. Overrides global ignoredRoutes for this instance
90
91
  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
92
+ headerBlacklist: [String], // Array of headers to omit from logs. Applied after any previous filters.
91
93
 
92
94
  ```
93
95
 
@@ -104,7 +106,7 @@ Use `expressWinston.errorLogger(options)` to create a middleware that log the er
104
106
  new winston.transports.Console()
105
107
  ],
106
108
  format: winston.format.combine(
107
- winston.format.colorize()
109
+ winston.format.colorize(),
108
110
  winston.format.json()
109
111
  )
110
112
  }));
@@ -120,19 +122,41 @@ The logger needs to be added AFTER the express router(`app.router)`) and BEFORE
120
122
  winstonInstance: <WinstonLogger>, // a winston logger instance. If this is provided the transports and formats options are ignored.
121
123
  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}` }
122
124
  baseMeta: Object, // default meta data to be added to log, this will be merged with the error data.
123
- metaField: String, // if defined, the meta data will be added in this field instead of the meta root object.
125
+ meta: Boolean, // control whether you want to log the meta data about the request (default to true).
126
+ 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.
127
+ requestField: [String] // the property of the metadata to store the request under (default 'req'). Set to null to exclude request from metadata
128
+ 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
124
129
  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.
125
130
  requestWhitelist: [String] // Array of request properties to log. Overrides global requestWhitelist for this instance
131
+ headerBlacklist: [String], // Array of headers to omit from logs. Applied after any previous filters.
126
132
  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.
127
133
  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
128
134
  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
129
135
  blacklistedMetaFields: [String] // fields to blacklist from meta data
136
+ skip: function(req, res, err) { return false; } // A function to determine if logging is skipped, defaults to returning false.
130
137
  ```
131
138
 
132
139
  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)`.
133
140
 
134
141
  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.
135
142
 
143
+ #### `metaField` option
144
+
145
+ In versions of `winston-middleware` prior to 4.0.0, this field functioned differently.
146
+
147
+ Previously the log entry would always have a "meta" field which would be set to the metadata of the request/error.
148
+ If `metaField` was set, this information would be stored as an object with the given property on the "meta" object of
149
+ the log entry. This prevented the use case where the metadata should be located at the root of the log entry.
150
+
151
+ In this version, `metaField` defaults to "meta" which maintains the prior versions behavior of storing the metadata at
152
+ a "meta" property of the log entry.
153
+
154
+ Explicitly setting the `metaField` to `null` or "null" causes the metadata to be stored at the root of the log entry.
155
+
156
+ The `metaField` option now also supports dot separated and array values to store the metadata at a nested location in the log entry.
157
+
158
+ <h3>Upgrade Note: For those upgrading from a version of `winston-middleware` prior to 4.0.0 that use the `metaField` property, to keep the same behavior, prepend `meta.` to your current `metaField` configuration. (i.e. 'foo' would become 'meta.foo')</h3>
159
+
136
160
  ## Examples
137
161
 
138
162
  ``` js
@@ -162,7 +186,7 @@ Alternatively, if you're using a winston logger instance elsewhere and have alre
162
186
  new winston.transports.Console()
163
187
  ],
164
188
  format: winston.format.combine(
165
- winston.format.colorize()
189
+ winston.format.colorize(),
166
190
  winston.format.json()
167
191
  )
168
192
  }));
@@ -176,7 +200,7 @@ Alternatively, if you're using a winston logger instance elsewhere and have alre
176
200
  new winston.transports.Console()
177
201
  ],
178
202
  format: winston.format.combine(
179
- winston.format.colorize()
203
+ winston.format.colorize(),
180
204
  winston.format.json()
181
205
  )
182
206
  }));
@@ -295,6 +319,60 @@ Browse `/error` will show you how winston-middleware handles and logs the errors
295
319
  "message": "middlewareError"
296
320
  }
297
321
 
322
+ ### StackDriver/Google Cloud Logging
323
+
324
+ If using this library with `@google-cloud/logging-winston`, use the following configuration to properly store httpRequest information.
325
+
326
+ See https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry
327
+
328
+ ```javascript
329
+ var express = require('express');
330
+ var expressWinston = require('winston-middleware');
331
+ var LoggingWinston = require('@google-cloud/logging-winston').LoggingWinston;
332
+
333
+ const app = express()
334
+
335
+ app.use(expressWinston.logger({
336
+ transports: [new LoggingWinston({})],
337
+ metaField: null, //this causes the metadata to be stored at the root of the log entry
338
+ responseField: null, // this prevents the response from being included in the metadata (including body and status code)
339
+ requestWhitelist: ['headers', 'query'], //these are not included in the standard StackDriver httpRequest
340
+ responseWhitelist: ['body'], // this populates the `res.body` so we can get the response size (not required)
341
+ dynamicMeta: (req, res) => {
342
+ const httpRequest = {}
343
+ const meta = {}
344
+ if (req) {
345
+ meta.httpRequest = httpRequest
346
+ httpRequest.requestMethod = req.method
347
+ httpRequest.requestUrl = `${req.protocol}://${req.get('host')}${req.originalUrl}`
348
+ httpRequest.protocol = `HTTP/${req.httpVersion}`
349
+ // httpRequest.remoteIp = req.ip // this includes both ipv6 and ipv4 addresses separated by ':'
350
+ httpRequest.remoteIp = req.ip.indexOf(':') >= 0 ? req.ip.substring(req.ip.lastIndexOf(':') + 1) : req.ip // just ipv4
351
+ httpRequest.requestSize = req.socket.bytesRead
352
+ httpRequest.userAgent = req.get('User-Agent')
353
+ httpRequest.referrer = req.get('Referrer')
354
+ }
355
+
356
+ if (res) {
357
+ meta.httpRequest = httpRequest
358
+ httpRequest.status = res.statusCode
359
+ httpRequest.latency = {
360
+ seconds: Math.floor(res.responseTime / 1000),
361
+ nanos: ( res.responseTime % 1000 ) * 1000000
362
+ }
363
+ if (res.body) {
364
+ if (typeof res.body === 'object') {
365
+ httpRequest.responseSize = JSON.stringify(res.body).length
366
+ } else if (typeof res.body === 'string') {
367
+ httpRequest.responseSize = res.body.length
368
+ }
369
+ }
370
+ }
371
+ return meta
372
+ }
373
+ }));
374
+ ```
375
+
298
376
  ## Global Whitelists and Blacklists
299
377
 
300
378
  winston-middleware exposes three whitelists that control which properties of the `request`, `body`, and `response` are logged:
@@ -324,6 +402,40 @@ Note that you can log the whole request and/or response body:
324
402
 
325
403
  expressWinston.requestWhitelist.push('body');
326
404
  expressWinston.responseWhitelist.push('body');
405
+
406
+ ### Nested Whitelists
407
+
408
+ `requestWhitelist` and `responseWhitelist` also support nested whitelist values, allowing access to parts of an object.
409
+
410
+ For example, using the following during logger setup:
411
+
412
+ expressWinston.responseWhitelist.push('body.import.value');
413
+
414
+ A response that looks like this :
415
+
416
+ {
417
+ body: {
418
+ important: {
419
+ value: 5
420
+ },
421
+ notImportant: {
422
+ value: 7
423
+ }
424
+ },
425
+ other: {
426
+ value: 3
427
+ }
428
+ }
429
+
430
+ Would only log the following value :
431
+
432
+ {
433
+ body: {
434
+ important: {
435
+ value: 5
436
+ }
437
+ }
438
+ }
327
439
 
328
440
  ## Route-Specific Whitelists and Blacklists
329
441
 
@@ -439,13 +551,9 @@ Run the basic Mocha tests:
439
551
 
440
552
  npm test
441
553
 
442
- Run the Travis-CI tests (which will fail with < 100% coverage):
443
-
444
- npm run test-travis
445
-
446
- Generate the `coverage.html` coverage report:
554
+ View the coverage report:
447
555
 
448
- npm run test-coverage
556
+ npx http-server coverage/lcov-report
449
557
 
450
558
  ## Issues and Collaboration
451
559
 
@@ -457,12 +565,14 @@ If you ran into any problems, please use the project [Issues section](https://gi
457
565
  * [Lars Jacob](https://github.com/jaclar) (https://github.com/jaclar)
458
566
  * [Jonathan Lomas](https://github.com/floatingLomas) (https://github.com/floatingLomas)
459
567
  * [Ross Brandes](https://github.com/rosston) (https://github.com/rosston)
568
+ * [Alex Kaplan](https://github.com/kapalex) (https://github.com/kapalex)
569
+ * [Matt Morrissette](https://github.com/yinzara) (https://github.com/yinzara)
460
570
 
461
571
  Also see AUTHORS file, add yourself if you are missing.
462
572
 
463
573
  ## MIT License
464
574
 
465
- Copyright (c) 2012-2014 Bithavoc.io and Contributors - http://bithavoc.io
575
+ Copyright (c) 2012 Bithavoc.io and Contributors - http://bithavoc.io
466
576
 
467
577
  Permission is hereby granted, free of charge, to any person obtaining a copy
468
578
  of this software and associated documentation files (the "Software"), to deal
package/index.d.ts ADDED
@@ -0,0 +1,115 @@
1
+ // Type definitions for winston-middleware 4.0
2
+ // Project: https://github.com/bithavoc/winston-middleware#readme
3
+ // Definitions by: Alex Brick <https://github.com/bricka>
4
+ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
5
+ // TypeScript Version: 2.3
6
+
7
+ import { ErrorRequestHandler, Handler, Request, Response } from 'express';
8
+ import { Format } from 'logform';
9
+ import * as winston from 'winston';
10
+ import * as Transport from 'winston-transport';
11
+
12
+ export interface FilterRequest extends Request {
13
+ [other: string]: any;
14
+ }
15
+
16
+ export interface FilterResponse extends Response {
17
+ [other: string]: any;
18
+ }
19
+
20
+ export type DynamicMetaFunction = (req: Request, res: Response, err: Error) => object;
21
+ export type DynamicLevelFunction = (req: Request, res: Response, err: Error) => string;
22
+ export type RequestFilter = (req: FilterRequest, propName: string) => any;
23
+ export type ResponseFilter = (res: FilterResponse, propName: string) => any;
24
+ export type RouteFilter = (req: Request, res: Response) => boolean;
25
+ export type MessageTemplate = string | ((req: Request, res: Response) => string);
26
+
27
+ export interface BaseLoggerOptions {
28
+ baseMeta?: object;
29
+ bodyBlacklist?: string[];
30
+ bodyWhitelist?: string[];
31
+ colorize?: boolean;
32
+ dynamicMeta?: DynamicMetaFunction;
33
+ expressFormat?: boolean;
34
+ format?: Format;
35
+ ignoreRoute?: RouteFilter;
36
+ ignoredRoutes?: string[];
37
+ level?: string | DynamicLevelFunction;
38
+ meta?: boolean;
39
+ metaField?: string;
40
+ requestField?: string;
41
+ responseField?: string;
42
+ msg?: MessageTemplate;
43
+ requestFilter?: RequestFilter;
44
+ requestWhitelist?: string[];
45
+ responseFilter?: ResponseFilter;
46
+ responseWhitelist?: string[];
47
+ headerBlacklist?: string[];
48
+ skip?: RouteFilter;
49
+ statusLevels?: {
50
+ error?: string;
51
+ success?: string;
52
+ warn?: string;
53
+ };
54
+ }
55
+
56
+ export interface LoggerOptionsWithTransports extends BaseLoggerOptions {
57
+ transports: Transport[];
58
+ }
59
+
60
+ export interface LoggerOptionsWithWinstonInstance extends BaseLoggerOptions {
61
+ winstonInstance: winston.Logger;
62
+ }
63
+
64
+ export type LoggerOptions = LoggerOptionsWithTransports | LoggerOptionsWithWinstonInstance;
65
+
66
+ export function logger(options: LoggerOptions): Handler;
67
+
68
+ export interface BaseErrorLoggerOptions {
69
+ baseMeta?: object;
70
+ dynamicMeta?: DynamicMetaFunction;
71
+ format?: Format;
72
+ level?: string | DynamicLevelFunction;
73
+ meta?: boolean;
74
+ metaField?: string;
75
+ requestField?: string;
76
+ msg?: MessageTemplate;
77
+ requestFilter?: RequestFilter;
78
+ requestWhitelist?: string[];
79
+ }
80
+
81
+ export interface ErrorLoggerOptionsWithTransports extends BaseErrorLoggerOptions {
82
+ transports: Transport[];
83
+ }
84
+
85
+ export interface ErrorLoggerOptionsWithWinstonInstance extends BaseErrorLoggerOptions {
86
+ winstonInstance: winston.Logger;
87
+ }
88
+
89
+ export type ErrorLoggerOptions = ErrorLoggerOptionsWithTransports | ErrorLoggerOptionsWithWinstonInstance;
90
+
91
+ export function errorLogger(options: ErrorLoggerOptions): ErrorRequestHandler;
92
+
93
+ export let requestWhitelist: string[];
94
+
95
+ export let bodyWhitelist: string[];
96
+
97
+ export let bodyBlacklist: string[];
98
+
99
+ export let responseWhitelist: string[];
100
+
101
+ export let ignoredRoutes: string[];
102
+
103
+ export let defaultRequestFilter: RequestFilter;
104
+
105
+ export let defaultResponseFilter: ResponseFilter;
106
+
107
+ export function defaultSkip(): boolean;
108
+
109
+ export interface ExpressWinstonRequest extends Request {
110
+ _routeWhitelists: {
111
+ body: string[];
112
+ req: string[];
113
+ res: string[];
114
+ };
115
+ }