3.0.0 • Published 2 years ago

starling-logger v3.0.0

Weekly downloads
-
License
SEE LICENSE IN LI...
Repository
github
Last release
2 years ago

starling-logger

Description

starling-logger is a colorful logger written in TypeScript with minimal dependencies that supports

  • different log types: 4 default types and custom types,
  • beautiful display of objects, colors for all primitives
  • HTTP request & response logging support,
  • determining the filename and the line on which logger method is called.

Log structure

By default logs have the following structure:

DATE | SCENE | LOG_TYPE | ...MESSAGES

In more detail,

MMM D, YYYY HH:mm:ss | file_name:line_of_code | LOG_TYPE | value1 value2 ... valueN

You can change the structure using Config.

Installation

Install the latest version

> npm install starling-logger

Install the specific version x.y.z

> npm instsall starling-logger@x.y.z

List of all versions can be found on NPM

Usage

Basic types

The starling-logger has 5 basic log types and 4 methods for them:

  • LOG (white) - log(...messages: any[]): string,
  • SUCCESS (green) - success(...messages: any[]): string,
  • INFO (green) - info(...messages: any[]): string,
  • WARNING (yellow) - warning(...messages: any[]): string,
  • ERROR (red) - error(...messages: any[]): string.

You pass values of any type using commas - the method beautifully combines them in one message.

Example:

/* app.ts */
import Logger from 'starling-logger';

/* ... */

const logger = new Logger();

logger.log("beautiful object", {
  objectOfClass: new Date(),
  number: 100,
  string: "starling",
  null: null,
  boolean: true,
  arrayOfValues: [
    null,
    undefined,
    17,
    19.1,
    true,
    false,
    "first name",
    "last name"
  ]
});
logger.success("App is listening on port", 8080);
logger.info("Service is ready for usage");
logger.warning("You propably shouldn't use this method in development mode");
logger.error(new Error("Something went wrong"));

Screenshot 2022-06-05 112401

Custom type

You can use your custom log type using

logCustom({
  type: '<input your type name>',
  color: '<select color from available LOG_COLORS>',
}, ...messages: any[])

Example

/* app.ts */
import Logger, { LOG_COLORS } from "starling-logger";

const logger = new Logger();

logger.logCustom(
  { type: "CUSTOM", color: LOG_COLORS.blue },
  "my awesome customized log"
);

const logTest = (...messages) =>
  logger.logCustom({ type: "TEST", color: LOG_COLORS.magenta }, ...messages);
logTest("test of custom log type");

image

HTTP request and response

interface RequestData {
  method?: string;
  url?: string;
}

interface ResponseData {
  statusCode?: number;
  responseTime?: number;
}

interface ResponseError {
  message: string;
}
logRequest(req: RequestData)
logResponse(req: RequestData, res: ResponseData, err: ResponseError)

Example for Express app

/* app.ts */

/* before all other middlewares */
app.use((req, res, next) => {
  req.startedAt = process.hrtime();
  logger.logRequest(req);
  next();
});

/* ... */

/* after all middlewares */
const hrtimeToMs = hrtime => {
  const msFloat = hrtime[0] * 1000 + hrtime[1] / 1000000;
  return parseInt(`${msFloat}`, 10);
};

/* response success */
app.use((req, res, next) => {
  res.responseTime = hrtimeToMs(process.hrtime(req.startedAt));
  logger.logResponse(req, res);
  next();
});

/* response error */
app.use((err, req, res, next) => {
  res.responseTime = hrtimeToMs(process.hrtime(req.startedAt));
  logger.logResponse(req, res, err);
  next();
});

"Go to line" feature in VSCode

This feature is supported by VSCode.

Since we have file_name:line_of_code in every log, you can click on it in the console and the search window fill be open with file_name:line_of_code filled.

image

Click on the correct file from the list and you will be taken to the line with which the logger method was called.

Return value

Instead of returning nothing as console.log does, starling-logger returns log as string.

const logger = new Logger();
const successMessage = logger.success('Connected!');
console.log(successMessage);

So you can use it for testing, outputing somewhere else or futher formatting.

All logger methods are tested with unit tests via Jest due to string return values.

Config

You can change logger configuration via loggerConfig passing it to the constructor when creating the logger instance.

class Logger {
  constructor(loggerConfig: LoggerConfig) { /* ... */ }
}
const logger = new Logger({ /* ... */ });
interface LoggerConfig {
  showDate?: boolean;
  scene?: string | null;
  output?: any;
}
const DEFAULT_LOGGER_CONFIG = {
  showDate: true,
  scene: null,
  output: console.log,
}

Date

starling-logger uses Moment to format dates. Current date format is "MMM D, YYYY HH:mm:ss"

You can hide date using { showDate: false } option in logger config.

const logger = new Logger({ showDate: false });

Disabling date may be useful for production because date might be already shown in some remote console tools.