• Stars
    star
    402
  • Rank 107,380 (Top 3 %)
  • Language
    TypeScript
  • License
    Other
  • Created about 13 years ago
  • Updated 26 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Caterpillar is the ultimate logging system for Deno, Node.js, and Web Browsers. Log levels are implemented to the RFC standard. Log entries can be filtered and piped to various streams, including coloured output to the terminal, the browser's console, and debug files. You can even write your own transforms.

Caterpillar

Status of the GitHub Workflow: bevry NPM version NPM downloads Dependency Status Dev Dependency Status
GitHub Sponsors donate button Patreon donate button Flattr donate button Liberapay donate button Buy Me A Coffee donate button Open Collective donate button crypto donate button PayPal donate button Wishlist browse button

Caterpillar is the ultimate logging system for Deno, Node.js, and Web Browsers. Log levels are implemented to the RFC standard. Log entries can be filtered and piped to various streams, including coloured output to the terminal, the browser's console, and debug files. You can even write your own transforms.

Usage

Complete API Documentation.

Examples

Overview

The RFC Log Levels are provided by the rfc-log-levels package which follows RFC 3164 - The BSD Syslog Protocol.

Log Entries that are within the lineLevel range, will have their line information fetched using the get-current-line package.

The Logger is what you write your log messages to, which you then pipe to destinations and transforms.

The Filter transport is used to filter out log levels that we do not want to pass onto the next destination.

The Human transport is used to convert the Log Entries into a human readable and colourful output.

The Browser transport is used to send the human output, including colours, to the Web Browser console.

The Transform is used to write your own transforms, and is what all the others are based from.

Node.js Guide

To get started for Node.js, setup a new Node.js project for this guide and install Caterpillar.

mkdir caterpillar-guide
cd caterpillar-guide
npm init
npm install --save caterpillar
touch index.js

Then edit our index.js file with the following, that will output all the log messages in JSON format to stdout, and can be run via node index.js:

const { Logger } = require('caterpillar')
const logger = new Logger()

logger.pipe(process.stdout)

logger.log('warn', 'this is a warning, which is level', 4)
logger.warn('this is a warning, which is level', 4)
logger.log('debug', 'this is a debug message, which is level', 7)
logger.warn('this is a debug message, which is level', 7)

Outputting in JSON format is not a nice experience, instead we can do better by using the Human transport such that it is human readable.

const { Logger, Human } = require('caterpillar')
const logger = new Logger()

logger.pipe(new Human()).pipe(process.stdout)

logger.log('warn', 'this is a warning, which is level', 4)
logger.warn('this is a warning, which is level', 4)
logger.log('debug', 'this is a debug message, which is level', 7)
logger.warn('this is a debug message, which is level', 7)

However, perhaps we want to still store the JSON format for querying later. We can pipe the human format to stdout as before, but we can pipe the raw output to a debug file.

const { Logger, Human } = require('caterpillar')
const logger = new Logger()

const { createWriteStream } = require('fs')
logger.pipe(createWriteStream('./debug.log'))

logger.pipe(new Human()).pipe(process.stdout)

logger.log('warn', 'this is a warning, which is level', 4)
logger.warn('this is a warning, which is level', 4)
logger.log('debug', 'this is a debug message, which is level', 7)
logger.warn('this is a debug message, which is level', 7)

Now let's stay for some reason, we want to capitalise all the log messages that are warning levels and higher, we can do this by making our own transport by extending the Transform.

const { Logger, Transform, Human } = require('caterpillar')
const logger = new Logger()

const { createWriteStream } = require('fs')
logger.pipe(createWriteStream('./debug.log'))

class Uppercase extends Transform {
    format(entry) {
        if (entry.levelNumber <= 4) {
            entry.args.forEach(function (value, index) {
                if (typeof value === 'string') {
                    entry.args[index] = value.toUpperCase()
                }
            })
        }
        return entry
    }
}

logger.pipe(new Uppercase()).pipe(new Human()).pipe(process.stdout)

logger.log('warn', 'this is a warning, which is level', 4)
logger.warn('this is a warning, which is level', 4)
logger.log('debug', 'this is a debug message, which is level', 7)
logger.warn('this is a debug message, which is level', 7)

Futhermore, the user probably doesn't need to see debug messages, even though they are useful for debugging. We can filter out the debug messages for the user, but maintain them for the debug.log file by applying the Filter transport to the pipe that goes to stdout.

const { Logger, Transform, Filter, Human } = require('caterpillar')
const logger = new Logger()

const { createWriteStream } = require('fs')
logger.pipe(createWriteStream('./debug.log'))

class Uppercase extends Transform {
    format(entry) {
        if (entry.levelNumber <= 4) {
            entry.args.forEach(function (value, index) {
                if (typeof value === 'string') {
                    entry.args[index] = value.toUpperCase()
                }
            })
        }
        return entry
    }
}

logger
    .pipe(new Filter({ filterLevel: 5 }))
    .pipe(new Uppercase())
    .pipe(new Human())
    .pipe(process.stdout)

logger.log('warn', 'this is a warning, which is level', 4)
logger.warn('this is a warning, which is level', 4)
logger.log('debug', 'this is a debug message, which is level', 7)
logger.warn('this is a debug message, which is level', 7)

As fetching line information is computationally expensive process, for large applications for performance we probably only want to fetch the line information for messages that we actually show to the user. As such, we should make the filterLevel and the lineLevel the same.

const { Logger, Transform, Filter, Human } = require('caterpillar')
const level = 5
const logger = new Logger({ lineLevel: level })

const { createWriteStream } = require('fs')
logger.pipe(createWriteStream('./debug.log'))

class Uppercase extends Transform {
    format(entry) {
        if (entry.levelNumber <= 4) {
            entry.args.forEach(function (value, index) {
                if (typeof value === 'string') {
                    entry.args[index] = value.toUpperCase()
                }
            })
        }
        return entry
    }
}

logger
    .pipe(new Filter({ filterLevel: 5 }))
    .pipe(new Uppercase())
    .pipe(new Human())
    .pipe(process.stdout)

logger.log('warn', 'this is a warning, which is level', 4)
logger.warn('this is a warning, which is level', 4)
logger.log('debug', 'this is a debug message, which is level', 7)
logger.warn('this is a debug message, which is level', 7)

Finally, if we are using Caterpillar in web browser environments, instead of Node.js, instead of doing:

const { Logger, Transform, Filter, Human } = require('caterpillar')
// ...
logger.pipe(new Human()).pipe(process.stdout)
// ...

We would pipe to the Browser transform instead of to stdout.

const { Logger, Transform, Filter, Human, Browser } = require('caterpillar')
// ...
logger.pipe(new Human()).pipe(new Browser())
// ...

With this, you now have enough information to leverage the cross-platform power of Caterpillar for most purposes, and the power to write your own custom transforms which can be published as their own packages and shared.

Install

npm

  • Install: npm install --save caterpillar
  • Import: import * as pkg from ('caterpillar')
  • Require: const pkg = require('caterpillar')

Skypack

<script type="module">
    import * as pkg from '//cdn.skypack.dev/caterpillar@^6.8.0'
</script>

unpkg

<script type="module">
    import * as pkg from '//unpkg.com/caterpillar@^6.8.0'
</script>

jspm

<script type="module">
    import * as pkg from '//dev.jspm.io/[email protected]'
</script>

Editions

This package is published with the following editions:

  • caterpillar/source/index.ts is TypeScript source code with Import for modules
  • caterpillar/edition-browsers/index.js is TypeScript compiled against ES2020 for web browsers with Import for modules
  • caterpillar aliases caterpillar/edition-es2019/index.js
  • caterpillar/edition-es2019/index.js is TypeScript compiled against ES2019 for Node.js 10 || 12 || 14 || 16 with Require for modules
  • caterpillar/edition-es2019-esm/index.js is TypeScript compiled against ES2019 for Node.js 12 || 14 || 16 with Import for modules

History

Discover the release history by heading on over to the HISTORY.md file.

Backers

Maintainers

These amazing people are maintaining this project:

Sponsors

No sponsors yet! Will you be the first?

GitHub Sponsors donate button Patreon donate button Flattr donate button Liberapay donate button Buy Me A Coffee donate button Open Collective donate button crypto donate button PayPal donate button Wishlist browse button

Contributors

These amazing people have contributed code to this project:

Discover how you can contribute by heading on over to the CONTRIBUTING.md file.

License

Unless stated otherwise all works are:

and licensed under:

More Repositories

1

cson

CoffeeScript-Object-Notation. Same as JSON but for CoffeeScript objects.
CoffeeScript
1,340
star
2

watchr

Better file system watching for Node.js. Provides a normalised API the file watching APIs of different node versions, nested/recursive file and directory watching, and accurate detailed events for file/directory changes, deletions and creations.
JavaScript
538
star
3

staticsitegenerators-website

Website containing the complete listing of static site generators
TypeScript
364
star
4

getmac

Get the mac address of the current machine you are on via Node.js
TypeScript
358
star
5

query-engine

QueryEngine provides extensive Querying, Filtering, and Searching abilities for Backbone.js Collections as well as JavaScript arrays and objects
CoffeeScript
328
star
6

dorothy

🧙🏻‍♀️ Bring your dotfile commands and configuration to any shell. Sensible defaults and hundreds of commands preloaded. Supports Bash, Zsh, Fish, Nu, Xonsh, Elvish, Dash, KornShell, macOS, Linux, Windows.
Shell
321
star
7

projectz

Stop wasting time maintaining your project's readme and package files! Let Projectz do it for you.
TypeScript
266
star
8

staticsitegenerators-list

A comprehensive, partially automatically generated comparison of static site generators
TypeScript
221
star
9

istextorbinary

Determine if a filename and/or buffer is text or binary. Smarter detection than the other solutions.
TypeScript
148
star
10

badges

The definitive rendering collection of badges
TypeScript
114
star
11

envfile

Parse and write environment files with Node.js
TypeScript
61
star
12

editions

📦 The best way to produce and consume the JavaScript packages you care about.
TypeScript
61
star
13

typechecker

Utilities to get and check variable types (isString, isPlainObject, isRegExp, etc)
TypeScript
49
star
14

taskgroup

Group together synchronous and asynchronous tasks and execute them with support for concurrency, naming, and nesting.
JavaScript
49
star
15

make-deno-edition

Automatically makes package.json projects (such as npm packages and node.js modules) compatible with Deno.
TypeScript
43
star
16

kava

Kava has been powering accurate test suites in node.js and the browser since 2012.
JavaScript
33
star
17

domain-browser

Node's domain module for the web browser
JavaScript
31
star
18

base

Base files for new projects
30
star
19

terraform-scaleway-hashistack

Terraform module to deploy Consul, Nomad, Vault onto Scaleway
Shell
20
star
20

boundation

Automatic scaffolding and upgrading of your JavaScript ecosystem projects using Bevry's best practices
JavaScript
19
star
21

safeps

Work with processes safely and easily in Node.js
JavaScript
17
star
22

filedirname

Fetch the current file and directory path, no matter your environment (Deno, Node.js, Web Browsers, ESM, CJS)
TypeScript
16
star
23

get-current-line

Get the current line number of the executing file and method
TypeScript
15
star
24

ambi

Ambi lets you execute any function ambidextrously; providing you the ability to execute any function (be it synchronous, asynchronous, returns, callbacks, promises) as if it returned a promise.
TypeScript
15
star
25

textextensions

The definitive listing of filename extensions that are used for text files.
TypeScript
13
star
26

coda-packs

Monorepo of Coda packs
TypeScript
12
star
27

daet

Minimal immutable date class that supports relative time, calendar time, and plus/minus of different units.
TypeScript
11
star
28

errlop

An extended Error class that envelops a parent error, such that the stack trace contains the causation
TypeScript
9
star
29

native-promise-pool

Create a pool of a specified concurrency that accepts promises
TypeScript
9
star
30

pluginclerk

 A clerk for retrieving compatible plugins from the npm database
TypeScript
9
star
31

event-emitter-grouped

Emit events in serial or parallel with support for synchronous and asynchronous listeners
JavaScript
9
star
32

awesome-crypto

The definitive listing of every cryptocurrency service; including their capabilities, fees, currencies, withdrawal process, etc.
9
star
33

extract-opts

Deprecated. Convert your API to promises
JavaScript
7
star
34

getsetdeep

Get or set nested variables of an object
TypeScript
7
star
35

sortobject

Deeply sort an object by its keys without mangling any arrays inside of it
TypeScript
7
star
36

scandirectory

Scan a directory recursively with a lot of control and power
TypeScript
7
star
37

safefs

Deprecated. Use the @bevry/fs-* packages instead
JavaScript
7
star
38

discourser

Discourse API Client written in TypeScript for Node.js and Browser environments
TypeScript
6
star
39

meetings

Bevry Meetings Website (WIP)
TypeScript
6
star
40

eachr

Deprecated: Use `for ( const [key, value] of Object.entries(thing) )`
TypeScript
6
star
41

binaryextensions

The definitive listing of filename extensions that are used for binary files.
TypeScript
6
star
42

arrangekeys

Returns a copy of a JavaScript object with the keys arranged in a specified order. Useful for formatting JSON files.
TypeScript
6
star
43

extendr

Utilities for cloning, extending, and de-referencing objects in shallow, deep, and safe ways
JavaScript
5
star
44

hooks

Aggregation of react hooks that we use. Such as useInterval and useMetaKey.
TypeScript
5
star
45

get-cli-arg

Deprecated. Use https://github.com/bevry/argument
TypeScript
5
star
46

cachely

A tiny wrapper that sits around your request function that caches its data for a specified duration, provides updates as requested rather than polling each interval
TypeScript
5
star
47

ropo

String replacement utilities with support for both synchronous and asynchronous replacements. Supports replacing Regular Expressions, HTML Elements, and Comment Elements. Compatible with async/await.
TypeScript
5
star
48

eslint-config-bevry

Bevry's ESLint configuration is an adaptive configuration that automatically configures ESLint
JavaScript
4
star
49

ansi

ANSI colors and styles for Deno, Node.js, JavaScript, and TypeScript
TypeScript
4
star
50

billing

Bevry's billing system
TypeScript
4
star
51

pluginloader

A class for loading, verifying, and creating plugins. Used by DocPad for years.
TypeScript
4
star
52

oneday

The number of milliseconds in one day
TypeScript
3
star
53

github-api

Interact with the GitHub API, fetching commits, repositories, members, and backers (authors, maintainers, contributors, funders, sponsors, donors)
TypeScript
3
star
54

start-of-week

Returns the start of the week based on the locale.
TypeScript
3
star
55

memo

Wrap a function in a memo to reuse the first invocation result of the function
TypeScript
3
star
56

progress-title

Your usual progress bar, but this time it is displayed within the terminal's title, which is much simpler
JavaScript
3
star
57

list

List/array/set utility functions: union, intersect, complement, unique, first, last, has, add, toggle
TypeScript
3
star
58

hostenv

Exports the correct PORT and HOSTNAME values for Heroku, AppFog, CloudFoundry, OpenShift, and other service environments
TypeScript
2
star
59

arrange-package-json

Arrange the properties in the package.json file to a universally consistent order
TypeScript
2
star
60

github-orgs

JSON listing of all the Bevry managed GitHub organisations
TypeScript
2
star
61

trim-indentation

Trim the initial indentation from a string
TypeScript
2
star
62

version-range

Check version ranges like `>=N` and `X || Y || Z` with support for Node.js, Web Browsers, Deno, and TypeScript.
TypeScript
2
star
63

docmatter

Battle tested SSG front matter parser. Extracted from DocPad. Delimiter lines have 3+ of the same character (such as /*** and ***/) allowing front matters to work with the syntax highlighting of your code editor. Supports custom parsers, e.g. --- cson. Parsers are handled externally.
CoffeeScript
2
star
64

mdx

MDX loader for Next.js
TypeScript
2
star
65

discourse-component-youtubetimestamps

Convert timetamps in your post, to a timestamped link to the post's (otherwise topic's) referenced youtube video
HTML
2
star
66

json

Helpers for reading and writing JSON.
TypeScript
2
star
67

designs

Designs and resources for our company, community, and products
2
star
68

version-compare

Compare two versions quickly
TypeScript
2
star
69

dominject

Inject scripts and styles into the DOM with duplicate prevention and completion callback support
JavaScript
2
star
70

normalify

Normalize different variable value types - e.g. `"1"` becomes `1`
TypeScript
2
star
71

nodejs-versions

Filter the absolute or significant Node.js versions by vast amounts of criteria, such as LTS status.
TypeScript
2
star
72

fs-accessible

Check if a path is accessible
TypeScript
1
star
73

requirefresh

Require a file without adding it into the require cache
TypeScript
1
star
74

logger-clearable

A logger that is clearable
JavaScript
1
star
75

valid-directory

Check whether or not the current working directory is valid on windows
TypeScript
1
star
76

valid-filename

Check if a string is a valid filename.
TypeScript
1
star
77

assert-helpers

Common utilities and helpers to make testing assertions easier
TypeScript
1
star
78

rfc-log-levels

A map of log level aliases matched to their numeric values. Follows the RFC Standard.
TypeScript
1
star
79

.github

1
star
80

duration-timestamp

Parse and stringify duration timestamps (such as hh:mm:ss and HhMmSs)
TypeScript
1
star
81

detect-indentation

Utility to detect indentation from a string
TypeScript
1
star
82

render

Render elements for HTML and Markdown
TypeScript
1
star
83

valid-module

Verify that file or package, be it remote, or local, is a valid ECMAScript Module
TypeScript
1
star
84

file-url-to-path

Convert a file: URL to its path
TypeScript
1
star
85

fellow

Fellow is a package for creating people that can be unified by their shared values via a singleton list on the class
TypeScript
1
star
86

unicode-symbols

Unicode Symbols
TypeScript
1
star
87

links

Collection of Links for Redirection on the Bevry websites
TypeScript
1
star
88

ignorepatterns

A regular expression that matches common filenames that we want to ignore
TypeScript
1
star
89

spinner-title

Write your spinner to the terminal title bar
TypeScript
1
star
90

ignorefs

Ignore common and custom patterns of the file system
TypeScript
1
star
91

ecmascript-versions

Get all ECMAScript versions, or the ECMAScript version that was ratified on a specific date.
TypeScript
1
star
92

unbounded

Function.prototype.bind replacement that provides an `unbounded` hidden property on the returned bounded function, that contains the original unbounded function
TypeScript
1
star
93

version-clean

Turn a dirty version (such as v1, =1.0.x, >1.0 <2) into a clean version (1.0)
TypeScript
1
star