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

node-chronicle

v1.0.0

Published

Simplified logging for node applications

Downloads

38

Readme

Simplified logging for node applications



Chronicle is built on top of all the great work done by "Sindre Sorhus" and other collaborators of the chalk project. This project is not directly associated with chalk other than chalk being a core dependency of Chronicle.

IMPORTANT: Please note that although Chronicle can be configured to any color through chalk, your output is subject to your terminal's color limitations.

Highlights

  • Fully configurable
  • Simple and Expressive API
  • Highly performant

Install

npm install node-chronicle

Usage

import Chronicle from 'chronicle';

const chronicle = new Chronicle();

chronicle.info('Info: sample application has started');
chronicle.warn('Warning: this is just a sample');
chronicle.error('Error: no application logic detected', true); // logs to logs/error.log file

Easily define your own logging mechanism and color-coding preference:

import Chronicle from 'chronicle';

const chronicle = new Chronicle({
  systemLogs: {
    blue: '#007cae', // indigo blue
    yellow: '#ae8f00', // bright orange
    red: 'red',
  },
});

chronicle.blue('Info: using custom method blue, sample application has started');
chronicle.yellow('Warning: using custom method yellow, this is just a sample');
chronicle.red('Error: using custom method red, no application logic detected', false);

Customize logging options to best suit your project

import Chronicle from 'chronicle';

const chronicle = new Chronicle({
  logToFileByDefault: true,
  logTimestamp: true,
  path: 'custom-logs', // <project root>/custom-logs/*.log
  prefix: '--------------------------------------------------------------- \n',
  suffix: '\n=============================================================== \n',
});

chronicle.info('Info: sample application has started');

Add additional log types extending the default options of "info", "warn", "error" and "debug"

import Chronicle from '../source/index.js';

const chronicle = new Chronicle({ additionalLogs: { question: 'green' } });

// create additional log with direct chalk configuration
chronicle.defineType('query', chronicle.chalk().black.bgGreen);

chronicle.question('What will a fully custom chalk color function look like?');
await chronicle.query('This is what a custom chalk color setting looks like', true);

API

Defining Logs & Colors

By default, Chronicle is instantiated with the following options:

  additionalLogs: {},
  systemLogs: {
    info: 'cyan',
    warn: 'yellow',
    error: 'red',
  },

You can add to a new log/color setting by passing the additionalLogs option to the Chronicle constructor. Any setting that already exists in systemLogs will be replaced, otherwise they will be added.

  const chronicle = new Chronicle({ additionalLogs: { info: 'green', custom: 'cyan' } });

  // output configuration:
  {
    info: 'green',
    warn: 'yellow',
    error: 'red',
    custom: 'cyan'
  }

Chronicle will generate convenience methods for all keys provided, with the corresponding color settings. The example above would create the following convenience methods, for logging:

  chronicle.info() // green output
  chronicle.warn() // yellow output
  chronicle.error() // red output
  chronicle.custom() // cyan output

These methods can then be called in your application with logging parameters.

Color settings are handled by determining whether your input is a color name or a hex value (prefixed with #). For example, passing red as a color setting will utilize chalk.red, while passing #ff0000 would use chalk.hex('#ff0000') instead. A list of available colors can be found in chalks' documentation.

Additionally, these methods return a promise when logToFile is true, allowing you use them with await in an async method, or append then(), catch(), or finally() for more advanced callback usage.

async method() {
  await chronicle.error('error message', true);

  // do something after logs/error.log (default) is created
}

The Debug Method

Chronicle allows for the chronicle.debug() method to be overridden by a color setting. However, by default we do not define a color for debug and debug is handled differently. For console logging, all debug does is output the following:

// For logging to console:
console.dir(content);

// For writing to file:
JSON.stringify(content, null, 2);

We believe that when wanting to output complicated objects or debug typescript applications, there are better methods than utilizing this Chronicle package. But for anyone who's fully incorporated Chronicle into their project, this function offers some convenience.

Logging Parameters

chronicle.error('error message', true, false); // content, logToFile, overwrite

| Parameter | Type | Default | Description | | :---: | :---: | :---: | :--- | | content | String | | Content of log that will output on your console. | | logToFile | Boolean | false | Option to log content to file. | | overwrite | Boolean | false (true on debug()) | Option to overwrite log file, rather than append to it. This option is redundant if logToFile is false. |

logToFile will log to /logs unless configured differently during instantiation.

Configuration

When instantiating Chronicle, you can pass an object to customize your settings. Below is the default configuration:

const chronicle = new Chronicle({
  logToFileByDefault: false,
  logTimestamp: false,
  path: 'logs/',
  prefix: '',
  suffix: '',
  additionalLogs: {},
  systemLogs: {
    info: 'cyan',
    warn: 'yellow',
    error: 'red',
  }
});

| Option | Type | Default | Description | | :---: | :---: | :---: | :--- | | logToFileByDefault | Boolean | false | Option to change default setting for logToFile parameter of logging functions. | | logTimestamp | Boolean | false | Option to include timestamp in console logging. Timestamps are automatically included in file logs. | | path | String | 'logs/' | Path in which to store log files. This setting is relative to your project's root directory. | | prefix | String | '' | Prefix string to prepend all log messages for all log types with the exception of debug. | | suffix | String | '' | Suffix string to tack on to all log messages for all log types with the exception of debug. | | additionalLogs | Object | | Key value pair object containing log type to color setting for logs that will be merged with systemLogs | | systemLogs | Object | | Key value pair object containing log type to color setting for main Chronicle logs available in application |

additionalLogs and systemLogs are explained with more detail in the defining logs and colors section.

Advanced Configuration

You may want to do more than just pick a basic color for your output. chalk offers a variety of different options, and can be configured via defineType(). Chronicle exposes the chalk instance via chalk() so that you don't have to import chalk directly into your project. Here is an example of how you can use this method to fully customize your log color setting:

const chronicle = new Chronicle();

chronicle.defineType('critical', chronicle.chalk().bold.red);
chronicle.critical('This is a critical error');

Additionally, any configuration that can be set during instantiation, can also be applied exclusively to any given type by passing in a third options parameter.

// params: type, setting, options
chronicle.definetype('notice', '#c0c0c0', {
  prefix: '--------------------------------------------------------------- \n',
  suffix: '\n=============================================================== \n'
});

defineType() params

| Parameter | Type | Description | | :---: | :---: | :--- | | type | String | Create or overwrites a logging function for the given type. | | setting | String or Function | Color setting or chalk function | | options | Object | Configure any setting only to the given type rather than globally. See configuration for list of options |

const chronicle = new Chronicle();

chronicle.defineType('info', chronicle.chalk().black.bgCyan);
chronicle.defineType('critical', chronicle.chalk().bold.red);
chronicle.defineType('dialog', 'magentaBright');
chronicle.definetype('notice', '#c0c0c0', {
  prefix: '--------------------------------------------------------------- \n',
  suffix: '\n=============================================================== \n'
});

chronicle.info('This pre-existing log now has a cyan background and black foreground');
chronicle.critical('This new log is bold and red');
chronicle.dialog('This new dialog is bright magenta');
chronicle.notice('This new log is the hex "#c0c0c0" share of gray');

defineType() can also be used as an alternative to populating the additionalLogs setting in the constructor, as if the setting doesn't already exist, it will then be created.

Origin

As a team of developers who are constantly working on side projects, we often litter our codebase with TODOs to refactor convenience utils such as chronicle into classes of their own, or projects of their own. This usually turns into internal tech debt that never gets addressed. Furthermore, we also often find ourselves going the copy -> paste -> modify route of previously written useful logic, which saves us time in new projects, but not as much as it would if all we had to do was run an npm install instead.

With that in mind, we are proud to release chronicle as an open source package, in hopes others will find this just as useful as we do in their own projects.

Maintainers