Code Monkey home page Code Monkey logo

woodlot's Introduction

woodlot icon

woodlot npm version NPM Downloads Patreon donate button

An all-in-one JSON logging utility that supports ExpressJS HTTP logging, custom logging, provides multi-format output and an easy to use events API.

  • Works as an HTTP logging middleware with ExpressJS
  • Support for custom logging with different logging levels
  • Provides log output in json format with request body/query params, headers and cookies
  • Support for Apache common and combined log formats as output
  • Multiple file stream support for log aggregation
  • Simple to use events API
  • Requires node >= 0.10

Installation

Using npm

npm install woodlot --save

Using yarn

yarn add woodlot

Usage

As an ExpressJS middleware

The woodlot middlewareLogger can be hooked into the existing ExpressJS middleware chain and can be used to log all HTTP requests.

Example -

var express = require('express');
var app = express();
var woodlot = require('woodlot').middlewareLogger;

app.use(
	woodlot({
		streams: ['./logs/app.log'],
		stdout: false,
		routes: {
			whitelist: ['/api', '/dashboard'],
			strictChecking: false
		},
		userAnalytics: {
			platform: true,
			country: true
		},
		format: {
			type: 'json',
			options: {
				cookies: true,
				headers: true,
				spacing: 4,
				separator: '\n'
			}
		}
	})
);

Options

streams {array}

This is an option that specifies the file stream endpoints where the generated logs will be saved. You can specify multiple streams using this option.

stdout {boolean} | Default: true

It specifies whether the generated log entry should be logged to the standard output stream i.e. process.stdout or not.

routes {object}

This option is used with the woodlot middlewareLogger. It specifies all the routes (with checking mode) for which logging is to be enabled. By default, log entry is generated for all the routes.

whitelist {array}

This option is used with the routes option to specify the route whitelist.

strictChecking {boolean} | Default: false

This option is used with the routes option to specify the checking mode for the route whitelist.

routes: {
    whitelist: ['/api'],
    strictChecking: false
}

For the above example, setting it to false will enable logging for all routes that have api in them. Example - /api, /api/getUser, /api/getUser/all, /userapi etc.

Whereas, setting it to true will only enable logging for the /api route.

userAnalytics {object}

Use this option to add user details to your logs.

platform {boolean} | Default: false

Use this option with userAnalytics, to specify whether to include user platform info in the logs or not i.e. browser, browserVersion, os, and osVersion.

country {boolean} | Default: false

Use this option with userAnalytics, to specify whether to include user country info in the logs or not i.e. name and isoCode.

The userAnalytics option will add the following info to your logs -

"userAnalytics": {
    "browser": "Chrome",
    "browserVersion": "60.0.3112.90",
    "os": "Mac OS",
    "osVersion": "10.11.6",
    "country": {
        "name": "India",
        "isoCode": "IN"
    }
}

format {object}

This option sets the log output format and other settings related to that particular format.

type {string} | Default: 'json'

The default output format is json. The middlewareLogger supports two more formats - common and combined, which are Apache's access log formats.

The generated output log for each format is as follows -

json
{
    "responseTime": "4ms",
    "method": "GET",
    "url": "/api",
    "ip": "127.0.01",
    "body": {},
    "params": {},
    "query": {},
    "httpVersion": "1.1",
    "statusCode": 200,
    "timeStamp": "23/Apr/2017:20:46:01 +0000",
    "contentType": "text/html; charset=utf-8",
    "contentLength": "4",
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
    "referrer": null,
    "userAnalytics": {
        "browser": "Chrome",
        "browserVersion": "60.0.3112.90",
        "os": "Mac OS",
        "osVersion": "10.11.6",
        "country": {
            "name": "India",
            "isoCode": "IN"
        }
    },
    "headers": {
        "host": "localhost:8000",
        "connection": "keep-alive",
        "accept-encoding": "gzip, deflate, sdch, br",
        "accept-language": "en-US,en;q=0.8,la;q=0.6"
    },
    "cookies": {
        "userId": "zasd-167279192-asknbke-0684"
    }
}

json format supports logging of body params and cookies. If you wish to log them, please make sure to enable the bodyParser and cookieParser middlewares before woodlot.

common
127.0.01 - - [23/Apr/2017:20:47:28 +0000] "GET /api HTTP/1.1" 200 4
combined
127.0.01 - - [23/Apr/2017:20:48:10 +0000] "GET /api HTTP/1.1" 200 4 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"

The timestamp generated in all logs is in ISO format.

options {object}

cookies {boolean} | Default: false

This option is to be used with the json format. It specifies whether you want to log request cookies or not.

Please make sure that the cookieParser middleware is enabled before woodlot, if this option is to be used.

headers {boolean} | Default: true

This option is to be used with the json format. It specifies whether you want to log request headers or not.

compact {boolean} | Default: false

This option is to be used with the json format. It specifies whether you want to log json as one line compact string.

NOTE spacing option will be ignored if this option is set to true.

spacing {string|number} | Default: \t

This option is to be used with the json format. It specifies the indentation for the generated log entry. You can specify a tab \t or numeric values 4, 8 for spaces.

separator {string} | Default: \n

This option can be used with any of the supported formats. It specfies the separator between two log entires. You can add a newline character \n, a whitespace or any other valid character.


Custom logging

The woodlot customLogger can be used to perform custom logging with different logging levels.

Example -

var express = require('express');
var app = express();
var woodlotCustomLogger = require('woodlot').customLogger;

var woodlot = new woodlotCustomLogger({
	streams: ['./logs/custom.log'],
	stdout: false,
	format: {
		type: 'json',
		options: {
			spacing: 4,
			separator: '\n'
		}
	}
});

app.get('/', function (req, res) {
	var id = 4533;
	woodlot.info('User id ' + id + ' accessed');
	return res.status(200).send({ userId: id });
});

Log levels

info
woodlot.info('Data sent successfully');
debug
woodlot.debug('Debugging main function');
warn
woodlot.warn('User Id is required');
err
woodlot.err('Server error occurred');

Options

streams {array}

See here.

stdout {boolean} | Default: true

See here.

format {object}

See here.

type {string} | Default: 'json'

The default output format is json. The customLogger supports one more format - text.

The generated output log for each format is as follows -

json
{
    "timeStamp": "23/Apr/2017:17:02:33 +0000",
    "message": "Data sent successfully",
    "level": "INFO"
}
text
INFO [23/Apr/2017:17:02:33 +0000]: "Data sent successfully"

options {object}

compact {boolean} | Default: false

This option is to be used with the json format. It specifies whether you want to log json as one line compact string.

NOTE spacing option will be ignored if this option is set to true.

spacing {string|number} | Default: \t

This option is to be used with the json format. It specifies the indentation for the generated log entry. You can specify a tab \t or numeric values 4, 8 for spaces.

separator {string} | Default: \n

This option can be used with any of the supported formats. It specfies the separator between two log entires. You can add a newline character \n, a whitespace or any other valid character.


Events

Woodlot emits events at various operations that can be used to track critical data.

Example -

var woodlotEvents = require('woodlot').events;

woodlotEvents.on('reqLog', function (log) {
	console.log('New log generated');
});

The returned log entry from each event will be of the same format as the one defined in the woodlot configuration.

middlewareLogger events

reqLog

This event is fired whenever a log entry is generated.

woodlotEvents.on('reqLog', function (log) {
	console.log('The following log entry was added - \n' + log);
});

:statusCode

This event is fired whenever a specific status code is returned from the request.

woodlotEvents.on('200', function (log) {
	console.log('Success!');
});
woodlotEvents.on('403', function (log) {
	console.log('Request forbidden!');
});

reqErr

This event is fired whenever an error is returned from the request.

All requests returning a status code of >=400 are considered to be errored. Please refer to the HTTP status codes guide for more info.

woodlotEvents.on('reqErr', function (log) {
	console.log('Errored!');
});

customLogger events

info

This event is fired whenever an info level log entry is generated.

woodlotEvents.on('info', function (log) {
	console.log('Info log - ' + log);
});

debug

This event is fired whenever a debug level log entry is generated.

woodlotEvents.on('debug', function (log) {
	console.log('Debug log - ' + log);
});

warn

This event is fired whenever a warn level log entry is generated.

woodlotEvents.on('warn', function (log) {
	console.log('Warn log - ' + log);
});

err

This event is fired whenever an err level log entry is generated.

woodlotEvents.on('err', function (log) {
	console.log('Error log - ' + log);
});

Contributors


Arun Michael Dsouza

Dhiraj Singh

Chen Li

Michael Samblanet

Anil Panghal

License

MIT License

Copyright (c) 2017 AdPushup Inc.

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.

woodlot's People

Contributors

aniladpushup avatar arunadpushup avatar arunmichaeldsouza avatar dhirajadpushup avatar msamblanet avatar sirius226 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

woodlot's Issues

body{} is showing empty when i send text type data from postman

Hi Team,

Below is the code how i initialize woodlot in my application.
consider i imported all required libs..

//logger
app.use(woodlot({ streams: ['./log/quotes.log'], stdout: false, routes: { whitelist: ['/','/rest/v1/quotes'], strictChecking: false }, userAnalytics: { platform: true, country: true }, format: { type: 'json', options: { cookies: true, headers: true, spacing: 4, separator: ',' } } }));

and when i hit the endpoint with some text in request body, i am not getting anything in body{ } part.
(POST req to my endpoint, no headers, no auth, in Body, it's just a text type)

er1

the response logged is:
{ "responseTime": "6ms", "method": "POST", "url": "/rest/v1/quotes", "ip": "::1", "body": {}, "params": {}, "query": {}, "httpVersion": "1.1", "statusCode": 200, "timeStamp": "15/Jul/2020:14:27:07 +0000", "contentType": "application/json; charset=utf-8", "contentLength": "56", "userAgent": "PostmanRuntime/7.26.1", "referrer": null, "userAnalytics": {}, "headers": { "content-type": "text/plain", "user-agent": "PostmanRuntime/7.26.1", "accept": "*/*", "postman-token": "94b2a128-84e3-496f-9b2b-f556960ffce7", "host": "localhost:3000", "accept-encoding": "gzip, deflate, br", "connection": "keep-alive", "content-length": "3" }, "cookies": {} },

and you can find body is empty..

but when i change body type to JSON, i am getting the data in body{ } part.
even i tried to change the 'type' field in 'format' section like:
type: 'text', or
type: 'text/html'
i am able to get the logs but body{ } is missing.

am i doing anything wrong ? How can i fix this ?

Logging json format as one-line compact string

Hi, is there a way for json format logger to log as one-line compact string?

It seems in utils.js all falsy values for spacing will be replaced by default value:
spacing = spacing || constants.DEFAULT_JSON_SPACING;

Could we support spacing = 0 as compact string flag or add another option compact: true/false?

Log to console without a file

If I attempt to configure woodlot to log to console and provide no streams, it logs the following message and does not finish initializing:

woodlot[warning]: Please provide at least one valid file stream to start logging. More info here - https://github.com/adpushup/woodlot

Based on a scan of the code this seems intentional but I have use cases where I do not need to log to a file (the stdout is collected and maintained) and in some cases (namely during dev) would like to preserve the console formatting...

I can workaround with a noop stream but based on scanning the code, it still formats the log to write to a file and then does nothing with it...

Would you be open to a PR to allow no streams to be specified if the console output is enabled?

Can you add custom log values?

Is there a way to pass additional properties to the logger? For instance:

logger = require('woodlot').middlewareLogger

app.use(function(req) {
  return logger.set('userId', req.user.id); // <-- add user id to the logger
});

app.use(logger({
  streams: './logs/mylogs.log',
  stdout: false,
  userAnalytics: {
    platform: true,
    userId: true, // <-- display the user id in logs
    country: false
  },
  format: {
    type: 'json',
    options: {
      cookies: true,
      headers: true,
      spacing: 4,
      separator: '\n'
    }
  }
}));

Access the log file with js

How can i access the log file within js?
Imagine i want to use the logger as json database. And if app crashes i need the last entry to pick up where it crashed...

Either enclose the all thing in an array, or separate the log entries with a comma?

Thanks, and awesome work BTW.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.