How to do it…

Let's aim to replicate what we had in Winston, at least in part, so it will be easier for you if you do full stack work, both client- and server-side. We want to have a logger object with methods such as .warn() and .info() that will display a given message in an appropriate color. Also, we don't want logs to be displayed in production. This leads us to the code as follows:

// Source file: src/logging/index.js

/* @flow */

import debug from "debug";

const WHAT_TO_LOG = "myapp:SERVICE:*"; // change this to suit your needs
const MIN_LEVEL_TO_LOG = "info"; // error, warn, info, verbose, or debug

const log = {
error() {},
warn() {},
info() {},
verbose() {},
debug() {}
};

const logMessage = (
color: string,
topic: string,
message: any = "--",
...rest: any
) => {
const logger = debug(topic);
logger.color = color;
logger(message, ...rest);
};

if (process.env.NODE_ENV === "development") {
localStorage.setItem("debug", WHAT_TO_LOG);

/* eslint-disable no-fallthrough */
switch (MIN_LEVEL_TO_LOG) {
case "debug":
log.debug = (topic: string, ...args: any) =>
logMessage("gray", topic, ...args);

case "verbose":
log.verbose = (topic: string, ...args: any) =>
logMessage("green", topic, ...args);

case "info":
log.info = (topic: string, ...args: any) =>
logMessage("blue", topic, ...args);

case "warn":
log.warn = (topic: string, ...args: any) =>
logMessage("brown", topic, ...args);

case "error":
default:
log.error = (topic: string, ...args: any) =>
logMessage("red", topic, ...args);
}
}

export { log };

Some important details:

  • The WHAT_TO_LOG constant lets you select which messages should be shown.
  • The MIN_LEVEL_TO_LOG constant defines the lowest level that will be logged.
  • The log object has a method for each severity level, as in Winston.
  • Finally, a non-operative log object is returned if we are not in development mode; all calls to logging methods will produce exactly nothing.
Note that we used fallthrough in the switch statement (no break statements in it!) to correctly build up the log object. It's not often that you can do this in a good way, and we had to shut up ESLint about it! 

We have the code we need; let's see an example of its usage.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.233.72