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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@wizim-dev/logger

v0.0.1

Published

Logger helper to log anything in node JS

Downloads

435

Readme

Logger

Logger helper for Nodejs application

Getting Started

To use this module in your project, install the npm package

npm install '@snark/logger'

Usage

import logger from './index';

function printConsole(info) {
    let str = `${info.timestamp} - ${info.level} - ${info.message}`;
    if (info.prefix) {
        str = `${info.prefix} - ${str}`;
    }
    if (info.suffix) {
        str = `${str} - ${info.suffix}`;
    }
    if (info.newLine === true) {
        str = `\n${str}`;
    }
    return str;
}

logger.formatConsole = logger.winston.format.combine(
    logger.winston.format.timestamp(),
    logger.winston.format.errors({stack: true}),
    logger.winston.format.colorize(),
    logger.winston.format.printf(printConsole)
);

logger.meta = {prefix: 'Test prefix'};

logger.addConsoleTransport();

logger.log('debug', 'test logging', {suffix: '\tFin du log', newLine: true});

Default Transports

You can add 2 default transports once it has been imported

addConsoleTransport(options)

The Console transport takes a few simple options:

  • level: Level of messages that this transport should log (default: debug).
  • silent: Boolean flag indicating whether to suppress output (default: false).
  • eol: string indicating the end-of-line characters to use (default: os.EOL)
  • stderrLevels: Array of strings containing the levels to log to stderr instead of stdout, for example ['error', 'debug', 'info']. (default: [])
  • consoleWarnLevels: Array of strings containing the levels to log using console.warn or to stderr (in Node.js) instead of stdout, for example ['warn', 'debug']. (default: [])
  • format: Logform formatter (default: See formatConsole)
  • handleExceptions: Handling Uncaught Exceptions with winston (default: true)

addMongoTransport(options)

The MongoDB transport takes the following options. 'db' is required:

  • level: Level of messages that this transport should log (default: debug).
  • silent: Boolean flag indicating whether to suppress output (default: false).
  • format: Logform formatter (default: See formatMongo
  • db: MongoDB connection uri. required
  • options: MongoDB connection parameters (default: {poolSize: 2, autoReconnect: true}).
  • collection: The name of the collection you want to store log messages in (default: 'log').
  • storeHost: Boolean indicating if you want to store machine hostname in logs entry, if set to true it populates MongoDB entry with 'hostname' field, which stores os.hostname() value.
  • username: The username to use when logging into MongoDB.
  • password: The password to use when logging into MongoDB. If you don't supply a username and password it will not use MongoDB authentication.
  • label: Label stored with entry object if defined.
  • capped: In case this property is true, winston-mongodb will try to create new log collection as capped (default: false).
  • cappedSize: Size of logs capped collection in bytes (default: 10000000).
  • cappedMax: Size of logs capped collection in number of documents.
  • tryReconnect: Will try to reconnect to the database in case of fail during initialization. Works only if db is a string. (default: false).
  • expireAfterSeconds: Seconds before the entry is removed. Works only if capped is not set.

addCustomTransport(transport)

Adding a custom transport is easy. All you need to do is accept any options you need, implement a log() method, and consume it with winston. In addition, there are additional transports written by members of the community.

Levels

Logging levels in winston conform to the severity ordering from most important to least important error, warn, info and debug

import logger from '@snark/logger'

logger.addConsoleTransport(
    {level: 'error'}
);

Formatter

You can override default transport with helpers formatConsole and formatMongo() before adding default transports

formatConsole

Default formatter used by addConsoleTransport()

function ignoreConsole(info) {
    if (info.ignoreConsole) {
        return false;
    }
    return info;
}

function customFormatUuid(info) {
    let uuid = gettingNamespace() || null; // internal method to retrieve namespace
    if (uuid) {
        info.uuid = uuid;
    }
    return info;
}

function objectToString(info, opts) {
    if (info.message && typeof info.message === 'object') {
        info.message = inspect(info.message, false, null, opts.colorize);
    }
    return info;
}

function printConsole(info) {
    let str = `${info.timestamp} - ${info.level} - ${info.message}`;
    if (info.uuid) {
        str = `${info.uuid} - ${str}`;
    }
    if (info.prefix) {
        str = `${info.prefix} - ${str}`;
    }
    if (info.stack) {
        str = `${str}\n${info.stack}`;
    }
    if (info.suffix) {
        str = `${str} - ${info.suffix}`;
    }
    if (info.newLine) {
        str = `\n${str}`;
    }
    return str;
}

formatConsole = format.combine(
    format(ignoreConsole)(),
    format.timestamp(),
    format(customFormatUuid)(),
    format(objectToString)(),
    format.colorize(),
    format.printf(printConsole)
);

formatMongo

Default formatter used by addMongoTransport()

function ignoreMongo(info) {
    if (info.ignoreMongo) {
        return false;
    }
    return info;
}

function customFormatUuid(info) {
    let uuid = gettingNamespace() || null; // internal method to retrieve namespace
    if (uuid) {
        info.uuid = uuid;
    }
    return info;
}

formatMongo = format.combine(
    format(ignoreMongo)(),
    format.timestamp(),
    format(customFormatUuid)(),
    format.uncolorize()
);

Meta

You can add global meta to each log request with setter meta and retrieve it with getter meta By adding {newLine: true} into global meta, each log will generate a new line before printing

import logger from '@snark/logger'

logger.meta = {env: process.env.NODE_ENV};

const meta = logger.meta;

Express Router

Use logger router method to log information about express routes The createRouter(options) method takes the following options.

  • level: Level of messages that this transport should log (default: info).
  • fields Fields from express request to log (default: ['hostname', 'method', 'originalUrl', 'path', 'params', 'protocol', 'query', 'route', 'subdomains']).
import logger from '@snark/logger'
import express from 'express';

const app = express();

let api = logger.createRouter();

api.get('/ping', function (req, res) {
    res.json({ping: true});
});

app.use('/1.0', api)

Namespace

namespaceExpressMiddleware()

Generate an uuid to each express request and store it into winston info stream

import express from 'express'
import logger from '@snark/logger'

const app = express();

app.use(logger.namespaceExpressMiddleware());

runInNamspace(method, uuid = uuid())

Helper method to create a namespace and generate an uuid for a specific method

import logger from '@snark/logger'

logger.addConsoleTransport();

logger.runInNamespace(function () {
    logger.info("Log with an uuid inside a method");
})

logger.runInNamespace(function () {
    logger.info("Log with an uuid equal to 'GLOBAL'");
}, 'GLOBAL')

setUuid(value)

Helper to directly set a namespace uuid.

import express from 'express'
import logger from '@snark/logger'

const app = express();

app.use((req, res, next) => {
    logger.setUuid('custom-uuid-set-for-each-request');
    next();
});

logger.addConsoleTransport();

Helper methods

createLogger(options)

Helper method to create the winston instance Automatically called when using any log or transport method A logger accepts the following parameters

| Name | Default | Description | | ------------- | --------------------------- | --------------- | | level | 'info' | Log only if info.level less than or equal to this level | | levels | winston.config.npm.levels | Levels (and colors) representing log priorities | | format | winston.format.json | Formatting for info messages | | transports | [] (No transports) | Set of logging targets for info messages | | exitOnError | true | If false, handled exceptions will not cause process.exit | | silent | false | If true, all logs are suppressed |

import logger from '@snark/logger'
const options = {}; // winston options

logger.createLogger(options);

winstonInstance

Helper method to get the real winston logger instance (null if not yet created)

import logger from '@snark/logger'

logger.createLogger();

const winstonInstance = logger.winstonInstance;

winstonInstance.debug('test');

winston

Helper method to get the winston object imported from winston module

import logger from '@snark/logger'

const winston = logger.winston;