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

cloudlogger-ts

v1.0.9

Published

Simple Logging library for emitting JSON formatted logs.

Downloads

42

Readme

CloudLogger.ts

npm@latest codecov pipeline status dependencies install size npm@downloads

semantic-release typescript license

Prescriptive logger for formatting console outputs into a JSON format. Effective for analyzing messages, and only emitting debug/noisy logs when an erroroneus situation occurs.

Table of contents

Motivation

CloudLogger is designed to be a simple logger for providing a consistent format across all NodeJS logging needs. It was designed to act in compliance with on-demand hosting platforms such as Lambda. It provides logging formats for Http, Metric (based off CloudWatchMetrics), as well as the default console output commands; Error, Info, Warning, Debug, etc.

In addition, it leverages a circular buffer to help reduce noisy log emission. When the ringbuffer is used, all filtered messages are retained up until a configurable amount. This way the buffer can output filtered messages when an error is encountered. This grants the benefit of filtering logs while surfacing diagnostic information on an as-needed exceptional basis.

Usage

The recommended way to use CloudLogger is create a LogFactory that will then instantiate copies across files where logging is desired. This way the buffer can be spread across the entire application and message sequencing is preserved regardless where the errors occur. For runtimes such as Lambda/Functions it's recommended to clear the Buffer upon the handler's entry. This way regardless of uncaught error's crashing a program developers are gauranteed a clean buffer upon subsequent executions.

Setup

1. Create a factory with desired configuration settings, and export the getLogger method for usage.

// LoggerUtil.ts
import { ILogger, LoggerConfig, LogLevel, LoggerFactory } from 'cloudlogger-ts';

const factory = new LoggerFactory({
    // Use the Lambda's function name:
    // ref: https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime
    name: process.env.AWS_LAMBDA_FUNCTION_NAME,
    // Alert logger to use ringBuffer
    flushOnError: true,
    // Allocate space for 100 filtered logPayloads
    maxBufferSize: 100,
    // Filter any message below Warning
    filterLogLevel: LogLevel.warn,
});

// Export function for usage across code.
export function getLogger(option?: LoggerConfig): ILogger {
    return factory.getLogger(option);
}

2. Create and use a custom logger with a unique name.

import { getLogger } from './LogUtil';
const logger = getLogger({ name: 'main.ts' });

logger.info('Returning response.);

Example:

// main.ts
import { getLogger } from './LogUtil';
const logger = getLogger({ name: 'main.ts' });

const robotsText = `
User-agent: *
Disallow: /
`;

function handler() {
    const response = {
        statusCode: 200,
        headers: {
            'Cache-Control': 'max-age=100',
            'Content-Type': 'text/plain',
            'Content-Encoding': 'UTF-8',
        },
        isBase64Encoded: false,
        body: robotsText,
    };
    logger.info('Returning response.', response);
    return response;
}

module.exports.handler = handler;

Output:

{
    "logName": "StubbedLambda::main.ts",
    "level": "INFO",
    "timestamp": "2021-08-16T01:06:58.821Z",
    "message": "Returning response.",
    "payload": {
        "statusCode": 200,
        "headers": {
            "Cache-Control": "max-age=100",
            "Content-Type": "text/plain",
            "Content-Encoding": "UTF-8"
        },
        "isBase64Encoded": false,
        "body": "\nUser-agent: *\nDisallow: /\n"
    },
    "size": "432 Bytes"
}

Logging

Logging levels in cloudlogger conform to RFC5425: severity of all levels is assumed to be numerically ascending from most important to least important.

Log Levels:

Log Levels are preset and non-configurable. The values set below are meant to provide sufficient coverage for all necessary logging.

export enum LogLevel {
    metric = 0,
    alert = 1,
    error = 2,
    warn = 3,
    info = 4,
    http = 5,
    verbose = 6,
    debug = 7,
    silly = 8,
}

Configuration

Logging configuration comes in two stages. The configuration to apply on the CoreLogger created by the LoggerFactory, and the configuration to apply on each individual LoggerInstance.

CoreLogger Config

| Property | Default | Description | | -------------- | ------- | --------------------------------------------------------------------------------------------- | | name | "" | Name to apply for all Logs | | filterLogLevel | info | Minimum LogLevel to emit Messages. | | flushOnError | false | Flag to indicate if filtered messages should be retained for emitting when error encountered. | | maxBufferSize | 50 | The amount of filtered logs to retain in the ringBuffer when flushOnError is set to true. | | silent | false | Flag to indicate whether to suppress all Logs | | delimitter | '::' | Delimitter to use when seperating log names. |

const factory = new LoggerFactory({
    name: 'CoreServiceName',
    // Alert logger to use ringBuffer
    flushOnError: true,
    // Allocate space for 100 filtered logPayloads
    maxBufferSize: 100,
    // Filter any message below Info
    filterLogLevel: LogLevel.info,
});

Logger Config

| Property | Default | Description | | -------- | ------- | -------------------------------------------------------------- | | name | "" | Name to apply for all logs emitted by specific Logger instance |

const logger = getLogger({ name: 'main.ts' });

Using a Logger

For general messages the Logger supports a message alongside an optional payload that will be formatted.

logger.alert('Event payload recieved', event);
logger.error('Exception encountered during callibrations', err);
logger.warn('Empty response encountered from Database.', response);
logger.info('This process has now started doing something.', process.ip);
logger.debug('Internal state captured:', stackTrace);
logger.verbose('Internal state checkpoint 2 reached:', snapshot);
logger.silly('Is this thing on?');

logger.metric(metricData);
logger.http(request, response, duration);

Flushing the Ringbuffer

Cloudlogger at the time of this writing does not provide interceptions into the NodeJS framework to catch thrown exceptions. In order to emit filtered messages, it is left up to the user to invoke logger.error(). When this occurs all previously buffered messages will be outputted to console up until the error itself.

const factory = new LoggerFactory({
    flushOnError: true,
    filterLogLevel: LogLevel.warn,
});
const logger = getLogger({ name: 'main.ts' });

logger.info('Hello world'); // Filtered, retained in buffer.
logger.warn('Warning world'); // Emitted directly to console out.
logger.debug('Debug world'); // Filtered, retained in buffer.
logger.error('Error world'); // Will emit, all messages.
logger.verbose('Error was encountered in the world'); // Filtered, retained in buffer until next error.

// Output order sequence in logs: warn, info, debug, error