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

capillary-logger

v1.2.0

Published

A logging library with hierarchical context

Downloads

6

Readme

Capillary

Codeship Badge npm version

Capillary is a logging library with hierarchical context attached to each message.

Usage

First import the logger for use

var capillary = require('capillary');
import { Logger } from 'capillary';

From there, you can instantiate and use a logger as one might expect. The logger exposes helper methods for logging at various severity levels.

let logger = new Logger();

logger.info('Attempting to connect to database.');
logger.error('Failed to connect to database.');

You can also log structured messages

logger.warn({ message: 'Unable to connect to rabbitmq', connectionString: '...', error: err }); 

Often, however, there is information you'd like to include with every message, to provide context. These are usually things like a request identifier, trace id, etc. It can become quite annoying to

  • thread this information throughout the code base purely for logging purposes
  • remember to include this information on each and every logger statement

When instantiating the logger, Capillary lets you specify this context.

logger = new Logger({ requestId: '123...' });
logger.info('Processing request...');

You can split off child loggers, which inherit their parents context:

let logger = new Logger({ requestId: '123...' });
let child = logger.split({ activity: 'Setup' });
// The following message will additionally include the requestId and the activity
child.info({ message: 'Reading data from database', databaseId: '456...' }); 

Sometimes, especially in dependency injection scenarios, you don't have all the context you would like when you split off a child. Instead, a method is called later (such as an initialize, configure, or service method) which adds additional context you'd like to capture in log messages. Splitting off a separate logger for this is often inconvenient.

To solve this, we've seen people modifying the context, and to make the intention of this clearer, we've added a an augment method

let logger = new Logger({ requestId: '123...' });

...

logger.augment({ currentStep: 'Phase1' });
logger.info({ message: 'Average computed successfully' });

When you augment the context, messages logged with any child loggers will include the updated context

let logger = new Logger({ requestId: '123...' });
let averageCalculationLogger = logger.split({ activity: 'Average Calculation' });
...
logger.augment({ currentStep: 'Phase1' });
...
// The following message will include currentStep: Phase1
child.info({ message: 'Average computed successfully' });
...
logger.augment({ currentStep: 'Phase2' });
...
// The following message will include currentStep: Phase2
child.info({ message: 'Average computed successfully' });
...
logger.augment({ currentStep: 'Phase3' });
...
// The following message will include currentStep: Phase3
child.error({ message: 'Failed to compute average', error: ... });

Accepting Capillary Loggers

If you are writing another library, and want to allow (but not require) the use of a capillary logger, you can check if the logger passed in is capillary compliant via the the isCapillaryCompatible property on the logger, as so:

if(parentLogger && parentLogger.isCapillaryCompatible) {
  this._logger = parentLogger.split({ component: 'my-library' });
} else {
  this._logger = parentLogger;
}

Asynchronicity

Because some plugins may be communicating with outside services, you may want to respond to failures to log specific messages. For this, we provide a logAsync method which returns a promise.

Plugins

Capillary supports a plugin architecture. Each message will be passed into each plugin in the order in which they were activated. This can perform custom transformations, filter based on custom logic, or log to custom sources. By default, the "console" plugin will be active, which logs each message as JSON to the console.

As soon as the first plugin is registered, however, the default console plugin will be replaced by the registered plugin.

class FileWriterPlugin extends capillary.AsyncPlugin {
  private filename: string;
  constructor(filename: string) {
    this.filename = filename;
  }
  process(message: any): Promise<any> {
    return new Promise((resolve, reject) => {
      const strMessage = JSON.stringify(message);
      fs.appendFile(this.filename, strMessage, err => {
        return err ? reject(err): resolve();
      });
    });
  }
}

logger.addPlugin(new FileWriterPlugin('logs.txt'));

Plugins come in two flavors: Sync and Async. Capillary makes the guarantee that any Sync plugins are run synchronously when possible. That is, if all of your plugins are synchronous, the entire thing will be executed synchronously.

ConsolePlugin

Writes each log message out to console after passing it through JSON.stringify.

Allows pretty printing, configurable through the following options:

  • prettyPrint
    • (default: false)
    • Enables or disables pretty printing altogether
  • seperator
    • (default: '')
    • Seperate each log message with some token
  • severityColors
    • (default: { trace: 'grey', debug: 'green', info: 'white', warn: 'yellow', error: 'red', fatal: 'bgRed' })
    • Specifies the colors to use for each severity level

MinimumSeverityPlugin

Filters and discards any messages whose severity is below a pre-defined level.

TimestampPlugin

Adds the current date and time to each message, using a configurable property name.

TypePrefixPlugin

Prefixes all top level properties of a message with a prefix based on typeof that property. This is for use with elastic search and microservices, which has trouble indexing fields of different types.