@cley_faye/boilerplate 3.4.1 → 3.7.0

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.
package/README.md CHANGED
@@ -318,6 +318,7 @@ It supports the following properties:
318
318
  - route: log all route called. Can be either a boolean or an express-winston configuration.
319
319
  In the later case, all properties are accepted except the winston instance, which is set
320
320
  separately.
321
+ More details in the "custom logging" section below.
321
322
  - error: log all errors. Accept a boolean, or an object with the "collapseNodeModules" boolean
322
323
  property.
323
324
  - logger: an instance of a winston logger.
@@ -366,6 +367,40 @@ root of the service, or an object with the following properties:
366
367
  - options: The options to pass to express static handler
367
368
  - route: The route under which the static files will be served
368
369
 
370
+ ### Custom logging
371
+ The default configuration (by setting `options.log.route: true`) allows some level of customization
372
+ of the actual logged data.
373
+ If a custom object is passed instead of `true`, the following will not automatically apply.
374
+
375
+ By default, all body content is logged.
376
+ To finely tune what body elements are logged on each route the `bodyLogger()` middleware can be
377
+ used.
378
+ It takes two parameters, the first one is an array of properties that *should* be logged, the second
379
+ one can be a custom object or a function returning a custom object with extra properties to log.
380
+
381
+ For example, for a login route, you might want to hide the provided password but still get some info
382
+ (note: this is an example, in practice you probably shouldn't care about this)
383
+
384
+ ```JavaScript
385
+ router.post(
386
+ "/login",
387
+ bodyLogger(
388
+ ["login"],
389
+ req => ({
390
+ passwordLength: req.body.password.length,
391
+ }),
392
+ ),
393
+ processLogin,
394
+ );
395
+ ```
396
+
397
+ In addition to excluding properties from the body of a request and adding custom properties, it can
398
+ be useful to always identify a request coming from a logged-in user.
399
+
400
+ You can provide a `userFromReq` property to the `options.log` configuration.
401
+ It should be a function that receive `req` as its argument and returns a string identifying the
402
+ logged-in user.
403
+
369
404
  ### Configuring global aspects of an Express App
370
405
 
371
406
  #### Configuring the template engine
@@ -1,11 +1,22 @@
1
- import expressWinston from "express-winston";
2
- import { Router } from "express";
3
- import { LogOptions } from "./pipelinebuilder.js";
1
+ import expressWinston, { BaseLoggerOptions } from "express-winston";
2
+ import { Request, Router } from "express";
3
+ import { LogOptions, UserFromReqFunc } from "./pipelinebuilder.js";
4
4
  export declare type LoggerOptions = expressWinston.LoggerOptions | boolean;
5
5
  interface ErrorLoggerConfiguration {
6
6
  collapseNodeModules?: boolean;
7
7
  }
8
8
  export declare type ErrorLoggerOptions = ErrorLoggerConfiguration | boolean;
9
+ export interface LoggingData {
10
+ extraLoggingData?: Record<string, unknown>;
11
+ }
12
+ export interface RequestWithLoggingData extends Request {
13
+ _cleyfayeLogging?: LoggingData;
14
+ _routeWhitelists?: {
15
+ body?: Array<string>;
16
+ };
17
+ }
18
+ /** Return the default value for route logger is it is set as `true` */
19
+ export declare const defaultRouteLoggerConfig: (userFromReq?: UserFromReqFunc | undefined) => BaseLoggerOptions;
9
20
  export declare const registerRouteLogger: (app: Router, logOptions?: LogOptions | undefined) => void;
10
21
  export declare const registerErrorLogger: (app: Router, logOptions?: LogOptions | undefined) => void;
11
22
  export {};
@@ -29,42 +29,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
29
29
  return (mod && mod.__esModule) ? mod : { "default": mod };
30
30
  };
31
31
  Object.defineProperty(exports, "__esModule", { value: true });
32
- exports.registerErrorLogger = exports.registerRouteLogger = void 0;
32
+ exports.registerErrorLogger = exports.registerRouteLogger = exports.defaultRouteLoggerConfig = void 0;
33
33
  const winston_1 = __importDefault(require("winston"));
34
34
  const express_winston_1 = __importDefault(require("express-winston"));
35
35
  const winston_js_1 = require("../winston.js");
36
- // High value because of colorize()
37
- const LOG_LEVEL_PADDING_SIZE = 19;
38
- /**
39
- * Collapse all lines containing /node_modules/ into an ellipsis
40
- */
41
- const filterNodeModules = function* (message) {
42
- let inNodeModules = false;
43
- const lines = message.split("\n");
44
- for (const line of lines) {
45
- if (/\/node_modules\//u.exec(line)) {
46
- if (!inNodeModules) {
47
- inNodeModules = true;
48
- yield "[...]";
49
- }
50
- }
51
- else {
52
- inNodeModules = false;
53
- yield line;
54
- }
55
- }
56
- };
57
- /**
58
- * Prefix all lines with the level and the timestamp if needed
59
- */
60
- const prefixOutput = (level, message, timestamp) => {
61
- const timestampPrefix = timestamp
62
- ? `${new Date().toISOString()} `
63
- : "";
64
- const levelPrefix = `${level.toString().padStart(LOG_LEVEL_PADDING_SIZE)}: `;
65
- return message.split("\n").map(line => `${timestampPrefix}${levelPrefix}${line}`)
66
- .join("\n");
67
- };
68
36
  const customRouteFormat = (outputTimestamp) => winston_1.default.format.printf((info) => {
69
37
  const meta = info.meta;
70
38
  // Clean the meta object from stuff displayed in the regular message
@@ -86,13 +54,27 @@ const customRouteFormat = (outputTimestamp) => winston_1.default.format.printf((
86
54
  }
87
55
  const metaString = JSON.stringify(info.meta);
88
56
  const finalMessage = `${info.message} ${metaString === "{}" ? "" : metaString}`;
89
- return prefixOutput(info.level, finalMessage, outputTimestamp);
57
+ return (0, winston_js_1.prefixOutput)(info.level, finalMessage, outputTimestamp);
90
58
  });
59
+ /** Return the default value for route logger is it is set as `true` */
60
+ const defaultRouteLoggerConfig = (userFromReq) => ({
61
+ meta: true,
62
+ requestWhitelist: ["body"],
63
+ responseWhitelist: [],
64
+ dynamicMeta: (req) => {
65
+ const castReq = req;
66
+ const data = { ...castReq._cleyfayeLogging?.extraLoggingData };
67
+ if (userFromReq)
68
+ data.user = userFromReq(req) ?? null;
69
+ return data;
70
+ },
71
+ });
72
+ exports.defaultRouteLoggerConfig = defaultRouteLoggerConfig;
91
73
  const registerRouteLogger = (app, logOptions) => {
92
- const { route, logger, timestamp } = logOptions ?? {};
74
+ const { route, timestamp, userFromReq } = logOptions ?? {};
93
75
  let extraConfig;
94
76
  if (typeof route === "boolean") {
95
- extraConfig = {};
77
+ extraConfig = (0, exports.defaultRouteLoggerConfig)(userFromReq);
96
78
  }
97
79
  else {
98
80
  extraConfig = { ...route };
@@ -110,20 +92,11 @@ const registerRouteLogger = (app, logOptions) => {
110
92
  colorize: true,
111
93
  msg: "{{req.method}} {{req.url}} {{res.statusCode}} {{res.responseTime}}ms",
112
94
  };
113
- if (logger) {
114
- app.use(express_winston_1.default.logger({
115
- transports: winston_js_1.transports,
116
- ...baseConfig,
117
- ...extraConfig,
118
- }));
119
- }
120
- else {
121
- app.use(express_winston_1.default.logger({
122
- transports: winston_js_1.transports,
123
- ...baseConfig,
124
- ...extraConfig,
125
- }));
126
- }
95
+ app.use(express_winston_1.default.logger({
96
+ transports: winston_js_1.transports,
97
+ ...baseConfig,
98
+ ...extraConfig,
99
+ }));
127
100
  };
128
101
  exports.registerRouteLogger = registerRouteLogger;
129
102
  const customErrorFormat = (outputTimestamp, config) => {
@@ -131,9 +104,9 @@ const customErrorFormat = (outputTimestamp, config) => {
131
104
  return winston_1.default.format.printf((info) => {
132
105
  const meta = info.meta;
133
106
  const finalMessage = collapseNodeModules
134
- ? [...filterNodeModules(meta.message)].join("\n")
107
+ ? [...(0, winston_js_1.filterNodeModules)(meta.message)].join("\n")
135
108
  : meta.message;
136
- return prefixOutput(info.level, finalMessage, outputTimestamp);
109
+ return (0, winston_js_1.prefixOutput)(info.level, finalMessage, outputTimestamp);
137
110
  });
138
111
  };
139
112
  const registerErrorLogger = (app, logOptions) => {
@@ -0,0 +1,5 @@
1
+ import { NextFunction, Request, Response } from "express";
2
+ export declare type ExtraLoggingDataType = Record<string, unknown> | undefined;
3
+ export declare type ExtraLoggingDataFunc = (req: Request) => Promise<ExtraLoggingDataType> | ExtraLoggingDataType;
4
+ export declare type ExtraLoggingData = ExtraLoggingDataFunc | Record<string, unknown>;
5
+ export declare const bodyLogger: (bodyProps?: string[] | undefined, extraLoggingData?: ExtraLoggingData | undefined) => (req: Request, res: Response, next: NextFunction) => void;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ * MIT License
5
+ *
6
+ * Copyright (c) 2021 Gabriel Paul "Cley Faye" Risterucci
7
+ *
8
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ * of this software and associated documentation files (the "Software"), to deal
10
+ * in the Software without restriction, including without limitation the rights
11
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ * copies of the Software, and to permit persons to whom the Software is
13
+ * furnished to do so, subject to the following conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be included in all
16
+ * copies or substantial portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ * SOFTWARE.
25
+ *
26
+ */
27
+ "use strict";
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.bodyLogger = void 0;
30
+ const setLogInfoInReq = (req, body, extraData) => {
31
+ const castReq = req;
32
+ if (body) {
33
+ if (!castReq._routeWhitelists)
34
+ castReq._routeWhitelists = {};
35
+ castReq._routeWhitelists.body = body;
36
+ }
37
+ if (extraData) {
38
+ castReq._cleyfayeLogging = { extraLoggingData: extraData };
39
+ }
40
+ };
41
+ const bodyLogger = (bodyProps, extraLoggingData) => (req, res, next) => {
42
+ const asyncFunc = async () => {
43
+ const extraLogData = typeof extraLoggingData === "function"
44
+ ? await extraLoggingData(req)
45
+ : extraLoggingData;
46
+ setLogInfoInReq(req, bodyProps, extraLogData);
47
+ };
48
+ asyncFunc()
49
+ .then(() => {
50
+ next();
51
+ })
52
+ .catch((error) => {
53
+ next(error);
54
+ });
55
+ };
56
+ exports.bodyLogger = bodyLogger;
@@ -1,4 +1,4 @@
1
- import express from "express";
1
+ import express, { Request } from "express";
2
2
  import { OptionsJson, OptionsUrlencoded, OptionsText, Options as OptionsRaw } from "body-parser";
3
3
  import winston from "winston";
4
4
  import { LoggerOptions, ErrorLoggerOptions } from "./logger.js";
@@ -24,11 +24,17 @@ export interface ComplexStaticDefinition {
24
24
  route?: string;
25
25
  }
26
26
  export declare type StaticDefinition = ComplexStaticDefinition | string;
27
+ export declare type UserFromReqFunc = (req: Request) => string | undefined;
27
28
  export interface LogOptions {
28
29
  route?: LoggerOptions;
29
30
  error?: ErrorLoggerOptions;
30
31
  logger?: winston.Logger;
31
32
  timestamp?: boolean;
33
+ userFromReq?: UserFromReqFunc;
34
+ }
35
+ export interface DefaultErrorHandlerConfig {
36
+ /** Set to true to allow server errors without a code to be sent as-is in the response */
37
+ noErrorFilter?: boolean;
32
38
  }
33
39
  export interface PipelineSettings {
34
40
  topLevels?: Array<RouterWithNullDef>;
@@ -39,7 +45,7 @@ export interface PipelineSettings {
39
45
  options?: {
40
46
  log?: LogOptions;
41
47
  middleware?: MiddlewareOptions;
42
- defaultErrorHandler?: boolean;
48
+ defaultErrorHandler?: boolean | DefaultErrorHandlerConfig;
43
49
  };
44
50
  }
45
51
  export default class PipelineBuilder {
@@ -30,31 +30,42 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
30
30
  };
31
31
  Object.defineProperty(exports, "__esModule", { value: true });
32
32
  const express_1 = __importDefault(require("express"));
33
+ const winston_js_1 = require("../winston.js");
33
34
  const logger_js_1 = require("./logger.js");
34
- const defaultErrorHandler = (err, req, res, next) => {
35
- if (!res.headersSent && err.statusCode) {
36
- const message = err.expose
37
- ? err.message
38
- : undefined;
39
- const accepted = req.accepts([
40
- "text",
41
- "html",
42
- "json",
43
- ]);
44
- if (accepted === "json") {
45
- res.status(err.statusCode).send({
46
- statusCode: err.statusCode,
47
- message,
48
- });
35
+ const defaultErrorHandler = (errorHandlerConfig) => (err, req, res, next) => {
36
+ const noErrorFilter = typeof errorHandlerConfig === "boolean"
37
+ ? false
38
+ : Boolean(errorHandlerConfig.noErrorFilter);
39
+ if (!res.headersSent) {
40
+ if (err.statusCode) {
41
+ const message = err.expose
42
+ ? err.message
43
+ : undefined;
44
+ const accepted = req.accepts([
45
+ "text",
46
+ "html",
47
+ "json",
48
+ ]);
49
+ if (accepted === "json") {
50
+ res.status(err.statusCode).send({
51
+ statusCode: err.statusCode,
52
+ message,
53
+ });
54
+ return;
55
+ }
56
+ if (message) {
57
+ res.status(err.statusCode).send(message);
58
+ }
59
+ else {
60
+ res.sendStatus(err.statusCode);
61
+ }
49
62
  return;
50
63
  }
51
- if (message) {
52
- res.status(err.statusCode).send(message);
53
- }
54
- else {
55
- res.sendStatus(err.statusCode);
64
+ if (!noErrorFilter) {
65
+ // eslint-disable-next-line @typescript-eslint/no-magic-numbers
66
+ res.status(500).send("An unexpected error occured");
67
+ return;
56
68
  }
57
- return;
58
69
  }
59
70
  next(err);
60
71
  };
@@ -88,6 +99,15 @@ class PipelineBuilder {
88
99
  createPipeline({ topLevels, routes, statics, postStatics, errorHandlers, options, }) {
89
100
  const { middleware, log, defaultErrorHandler: useDefaultErrorHandler } = options ?? {};
90
101
  this.internalLog("createPipeline()");
102
+ if (log) {
103
+ const errorConfig = typeof log.error === "boolean"
104
+ ? {}
105
+ : log.error ?? {};
106
+ (0, winston_js_1.setConfig)({
107
+ timestamp: log.timestamp ?? false,
108
+ collapseNodeModules: errorConfig.collapseNodeModules ?? true,
109
+ });
110
+ }
91
111
  const router = express_1.default.Router();
92
112
  this.internalLog("setGenericMiddlewares()");
93
113
  this._setGenericMiddlewares(router, middleware);
@@ -247,10 +267,10 @@ class PipelineBuilder {
247
267
  (0, logger_js_1.registerErrorLogger)(router, logOptions);
248
268
  }
249
269
  }
250
- _setDefaultErrorHandler(router, enableDefaultErrorHandler) {
251
- if (enableDefaultErrorHandler) {
270
+ _setDefaultErrorHandler(router, defaultErrorHandlerConfig) {
271
+ if (defaultErrorHandlerConfig) {
252
272
  this.internalLog("Adding default error handler");
253
- router.use(defaultErrorHandler);
273
+ router.use(defaultErrorHandler(defaultErrorHandlerConfig));
254
274
  }
255
275
  }
256
276
  }
package/lib/express.d.ts CHANGED
@@ -23,6 +23,9 @@ import { PipelineSettings, LogFunction } from "./express/pipelinebuilder.js";
23
23
  * If the request accepts json, a json object with the error is returned.
24
24
  * Otherwise text is returned.
25
25
  *
26
+ * For convenience, providing timestamp and collapseNodeModules here will automatically
27
+ * update the basic consoleLogger configuration.
28
+ *
26
29
  * @param settings
27
30
  *
28
31
  * @param [settings.topLevels]
package/lib/express.js CHANGED
@@ -51,6 +51,9 @@ const pipelinebuilder_js_1 = __importDefault(require("./express/pipelinebuilder.
51
51
  * If the request accepts json, a json object with the error is returned.
52
52
  * Otherwise text is returned.
53
53
  *
54
+ * For convenience, providing timestamp and collapseNodeModules here will automatically
55
+ * update the basic consoleLogger configuration.
56
+ *
54
57
  * @param settings
55
58
  *
56
59
  * @param [settings.topLevels]
package/lib/winston.d.ts CHANGED
@@ -1,3 +1,17 @@
1
1
  import winston from "winston";
2
+ /**
3
+ * Collapse all lines containing /node_modules/ into an ellipsis
4
+ */
5
+ export declare const filterNodeModules: (message: string) => Generator<string>;
6
+ /**
7
+ * Prefix all lines with the level and the timestamp if needed
8
+ */
9
+ export declare const prefixOutput: (level: string, message: string, timestamp: boolean | undefined) => string;
10
+ export interface LogConfig {
11
+ timestamp: boolean;
12
+ collapseNodeModules: boolean;
13
+ }
14
+ /** Edit the configuration applied to consoleLogger */
15
+ export declare const setConfig: (config: LogConfig) => void;
2
16
  export declare const transports: winston.transports.ConsoleTransportInstance[];
3
17
  export declare const consoleLogger: winston.Logger;
package/lib/winston.js CHANGED
@@ -29,11 +29,61 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
29
29
  return (mod && mod.__esModule) ? mod : { "default": mod };
30
30
  };
31
31
  Object.defineProperty(exports, "__esModule", { value: true });
32
- exports.consoleLogger = exports.transports = void 0;
32
+ exports.consoleLogger = exports.transports = exports.setConfig = exports.prefixOutput = exports.filterNodeModules = void 0;
33
33
  const winston_1 = __importDefault(require("winston"));
34
+ // High value because of colorize()
35
+ const LOG_LEVEL_PADDING_SIZE = 19;
36
+ /**
37
+ * Collapse all lines containing /node_modules/ into an ellipsis
38
+ */
39
+ const filterNodeModules = function* (message) {
40
+ let inNodeModules = false;
41
+ const lines = message.split("\n");
42
+ for (const line of lines) {
43
+ if (/\/node_modules\//u.exec(line)) {
44
+ if (!inNodeModules) {
45
+ inNodeModules = true;
46
+ yield "[...]";
47
+ }
48
+ }
49
+ else {
50
+ inNodeModules = false;
51
+ yield line;
52
+ }
53
+ }
54
+ };
55
+ exports.filterNodeModules = filterNodeModules;
56
+ /**
57
+ * Prefix all lines with the level and the timestamp if needed
58
+ */
59
+ const prefixOutput = (level, message, timestamp) => {
60
+ const timestampPrefix = timestamp
61
+ ? `${new Date().toISOString()} `
62
+ : "";
63
+ const levelPrefix = `${level.toString().padStart(LOG_LEVEL_PADDING_SIZE)}: `;
64
+ return message.split("\n").map(line => `${timestampPrefix}${levelPrefix}${line}`)
65
+ .join("\n");
66
+ };
67
+ exports.prefixOutput = prefixOutput;
68
+ const logConfig = {
69
+ timestamp: true,
70
+ collapseNodeModules: true,
71
+ };
72
+ const customFormat = winston_1.default.format.printf((info) => {
73
+ const message = ("stack" in info) ? info.stack : info.message;
74
+ const filteredMessage = logConfig.collapseNodeModules
75
+ ? [...(0, exports.filterNodeModules)(message)].join("\n")
76
+ : message;
77
+ return (0, exports.prefixOutput)(info.level, filteredMessage, logConfig.timestamp);
78
+ });
79
+ /** Edit the configuration applied to consoleLogger */
80
+ const setConfig = (config) => {
81
+ Object.assign(logConfig, config);
82
+ };
83
+ exports.setConfig = setConfig;
34
84
  exports.transports = [new winston_1.default.transports.Console()];
35
85
  exports.consoleLogger = winston_1.default.createLogger({
36
86
  level: "info",
37
- format: winston_1.default.format.combine(winston_1.default.format.colorize(), winston_1.default.format.simple()),
87
+ format: winston_1.default.format.combine(winston_1.default.format.colorize(), customFormat),
38
88
  transports: exports.transports,
39
89
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cley_faye/boilerplate",
3
- "version": "3.4.1",
3
+ "version": "3.7.0",
4
4
  "description": "Boilerplate code generator for generic projects",
5
5
  "repository": {
6
6
  "type": "git",
@@ -17,13 +17,13 @@
17
17
  },
18
18
  "homepage": "https://github.com/CleyFaye/boilerplate#readme",
19
19
  "devDependencies": {
20
- "@keeex/eslint-config": "^1.7.0",
20
+ "@keeex/eslint-config": "^1.7.1",
21
21
  "@types/express": "^4.17.11",
22
22
  "@types/grunt": "^0.4.25",
23
23
  "@types/http-errors": "^1.8.0",
24
24
  "@types/node": "^16.0.0",
25
- "@typescript-eslint/eslint-plugin": "^5.3.1",
26
- "@typescript-eslint/parser": "^5.3.1",
25
+ "@typescript-eslint/eslint-plugin": "^5.12.0",
26
+ "@typescript-eslint/parser": "^5.12.0",
27
27
  "eslint": "^8.7.0",
28
28
  "eslint-plugin-import": "^2.25.4",
29
29
  "eslint-plugin-promise": "^6.0.0",