npm package: @kdg/loggojs
Description: Simple Transport based and extendable Javascript Logger
Author: Marcel Hinsch
Latest version: 1.0.3

# Loggo
#### (Pronounced Log-Go)
### Simple Transport based and extendable Javascript Logger
![](https://img.shields.io/npm/v/@kdg/loggojs.svg?style=popout) [![Coverage Status](https://coveralls.io/repos/bitbucket/kdgat/loggojs/badge.svg)](https://coveralls.io/bitbucket/kdgat/loggojs) ![](https://img.shields.io/npm/dt/@kdg/loggojs.svg?style=popout) ![](https://img.shields.io/bitbucket/issues/kdgat/loggojs.svg?style=popout) ![](https://img.shields.io/npm/l/@kdg/loggojs.svg?style=popout)

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
```sh
npm install @kdg/loggojs
```

## Usage
It's recommended that you create a new Logger instance. It's as simple as calling `new`!
```js
// 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!
```js
// 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!
```js
lg.info("Hello World!");
> "[Info][source]Hello World!"
```

Or use the global Logger:
```js
Logger.transports.console.level = "DEBUG";
Logger.warn("Watch out!");
> "[Warning][GLOBAL]Watch out!"
```
The global logger uses the globally defined transports internally.
### Available methods
```js
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.
```js
// 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
```
```js
// 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](#base-transport-options)
## Advanced Usage
### Add your own Transport to a Logger
```js
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.
```js
Logger.transports;
```
### Register global Transport
A transport needs to have a `__register` function in order to be a valid global Transport.<br>
You can still use Transports without this function as local Transports.
```js
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.
```js
// 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
```js
// Level can either be numeric or a Levelstring
lg.logMessage(level, ...message)
```
### Create a linked child of a Transport
```js
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()`
```js
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.
```js
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.
```