npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

starling-logger

v3.0.0

Published

Colorful logger for NodeJS apps

Downloads

17

Readme

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 [email protected]

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.