@kdg/loggojs

1.0.3 • Public • Published

Loggo

(Pronounced Log-Go)

Simple Transport based and extendable Javascript Logger

Coverage Status

Yet another logging library focused on simplicity and extensibility.

But why?

Because I can. And because current Logging implementations felt a little too overengineered for me.

Features

  • Simple Get to logging in just 3 (4 if you count the require) lines of code.
  • Transport based Logging
    • Console Transport: Log to the NodeJS console or Devtools.
  • Multiple Logger instances Different Transports and log levels for each instance.
  • Global Logging instance Only need quick logger functions? Use the global logger.
  • Easy to write new Transports Write a class that extends BaseTransport and define a log method.
  • Linked Transport Children Have a transport you like the way it's set up? Create a child that is directly linked to its parent transport. Changes on the parent affect the child if the child doesn't overwrite the change!
  • Queued Calling logging functions adds the message to a queue.
  • Async Logging functions return a promise that resolves when the queue is empty and all messages are logged.
  • Familiar Syntax Exposes the same logging functions as console and can be used as a drop in replacement.
  • Custom Log Levels Extend the existing log levels with custom named ones.

Installation

npm install @kdg/loggojs

Usage

It's recommended that you create a new Logger instance. It's as simple as calling new!

// Create a new Logger
const lg = new Logger("source");

Now that this is done, don't forget to set the level of your transports, otherwise they are disabled!

// Sets the transport level for this logger transport
// Possible values are "TRACE", "DEBUG", "INFO", "WARNING", "ERROR" or any numeric value
// See the values of Logger.Levels for all named levels
lg.transports.console.level = "INFO"

We are now ready to log messages!

lg.info("Hello World!");
> "[Info][source]Hello World!"

Or use the global Logger:

Logger.transports.console.level = "DEBUG";
Logger.warn("Watch out!");
> "[Warning][GLOBAL]Watch out!"

The global logger uses the globally defined transports internally.

Available methods

lg.trace(message);  // Level: Trace (0)
lg.debug(message);  // Level: Debug (1)
lg.info(message);   // Level: Info (2)
lg.warn(message);   // Level: Warning (3)
lg.error(message);  // Level: Error (4)
lg.log(message);    // Level: -1

Transport Options

Base Transport Options

All Transports share these options.

// Get or set the log level of the current Transporter
// Set to `false` to disable transport
// Available levels: "TRACE", "DEBUG", "INFO", "WARNING", "ERROR" or any numeric value
Transport.level;
> false
Transport.level = "WARNING";
Transport.level;
> 3
// Get or set the message format of the Transporter output
// The following variables are available and string-format is used to insert them
// Text: {level}, {text}, {source}
// Time: {y}, {m}, {d}, {h}, {i}, {s}, {ms}, {z}
Transport.format;
> "[{level}][{source}]{text}"

Console Transport

See Base Transport Options

Advanced Usage

Add your own Transport to a Logger

const newTransport = new Transport;
lg.transports["newTransportName"] = newTransport;

Access global Transports

These transports get linked to as children for every new Logger that is created.

Logger.transports;

Register global Transport

A transport needs to have a __register function in order to be a valid global Transport.
You can still use Transports without this function as local Transports.

const newGlobalLogger = require("./newGlobalLogger.js")
Logger.use(newGlobalLogger);

Format function

Set the format property of a Transport to a function instead of a string to have it evaluated.

// The format object has the following properties
const formatObject = {
    level,      // Numeric Loglevel value
    text,       // The log message
    source,     // The source the Logger has been created with
    y,          // Year
    m,          // Month
    d,          // Day
    h,          // Hour
    i,          // Minute
    s,          // Second
    ms,         // Millisecond
    z           // Timezone Offset
}
Transport.format = function(formatObject) {
    return "Some New Value";
}

Custom Loglevel

Use a custom level when doing logging

// Level can either be numeric or a Levelstring
lg.logMessage(level, ...message)

Create a linked child of a Transport

lg.transports.console.level = 4;

const child = lg.transports.console.createChild();

lg.transports.console.level;
> 4
child.level;
> 4

lg.transports.console.level = 2;
child.level
> 2

child.level = 1;
lg.transports.console.level = 3;
child.level;
> 1;

delete child["level"];
child.level;
> 3

Custom Transport

A custom Transport extends Loggo's BaseTransport class and implements an async (returns a Promise) function log()

const BaseTransport = require("Loggo/BaseTransport");

class MySimpleTransport extends BaseTransport {
    async log(level, source, ...message) {
        // Output the log somewhere, for example a file
    }
}

Transports support multiple special methods.

class MyComplexTransport extends MySimpleTransport {
    // Decide during runtime if this Transport should do logging, for example
    // you can check if this Transport is used in a main or a render process of electron
    // and decide based on that
    canLog() {
        if (runtimeLogCondition) return true;
        else return false;
    }

    // This property can either be a function or a static Object
    // It is required for a global Transport
    static __register() {
        return {
            type: "transport",
            name: "tComplex"
        };
    }
}

Issues

Feel free to submit issues and enhancement requests.

Contributing

This repository follows the "fork-and-pull" Git workflow:

  1. Fork the repo on GitHub
  2. Clone the project to your own machine
  3. Commit changes to your own branch
  4. Push your work back up to your fork
  5. Submit a Pull request so that we can review your changes

NOTE: Be sure to merge the latest from "upstream" before making a pull request!

Build the docs by running npm run build-docs. The ./html-docs directory contains the JSDoc/HTML version of the docs, the ./docs directory contains the markdown documentation.

Copyright and Licensing

This project is licensed under the MIT license.

This project does not require you to assign the copyright of your contributions, you retain the copyright. This project does require that you make your contributions available under the MIT license in order to be included in the main repo.

If appropriate, include the MIT license summary at the top of each file along with the copyright info. If you are adding a new file that you wrote, include your name in the copyright notice in the license summary at the top of the file.

License Summary

You can copy and paste the MIT license summary from below.

MIT License

Copyright (c) 2019 kdg mediascope, Marcel Hinsch

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Package Sidebar

Install

npm i @kdg/loggojs

Weekly Downloads

0

Version

1.0.3

License

MIT

Unpacked Size

705 kB

Total Files

57

Last publish

Collaborators

  • mhinsch
  • wolvan