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

riviere

v0.3.0

Published

log inbound/outbound HTTP traffic

Downloads

86

Readme

NPM

Coverage Status

riviere

The riviere module decorates your Koa middleware chain with inbound/outbound HTTP traffic logs.

Use riviere if you want an easy way to log all the HTTP traffic for your server. riviere works independently of your logging library, if you use any.


Table of contents

  1. Features
  2. Example logs
  3. Requirements
  4. Installation
  5. Usage
  6. Configuration
  7. Available Options
    1. bodyKeys
    2. color
    3. context
    4. errors.callback
    5. headersRegex
    6. health
    7. outbound.enabled
    8. traceHeaderName
  8. License

Features

  • Log all the HTTP(s) requests that are coming into your server and the corresponding responses. (inbound_request/outbound_response)
  • Log all the HTTP(s) requests that your server sends to any external systems and the corresponding responses. (outbound_request/inbound_response)
  • Log any unhandled errors that are thrown inside a requests's context.

Upcoming Features:

  • Support any logger that is able to format json objects into log messages (like log4js, winston, pino, etc ...)

Example logs

alt text

The above example logs are generated by executing:

curl localhost:3000 -H "X-myHeader: myHeaderValue"

Assuming that the following example server is running: examples/hello_with_outgoing_traffic.js


Requirements

  • Node version >= 8
  • Koa version >= 2

Installation

npm i --save riviere


Usage

Example:

const Koa = require('koa');
const Riviere = require('riviere');

const app = new Koa();

app.use(Riviere.middleware());
app.use(async function(ctx) {
    ctx.body = 'Hello World';
});

app.listen(3000);

Example with outbound HTTP traffic:

const Koa = require('koa');
const Riviere = require('riviere');

// this is just an example, you can use any http library
const rp = require('request-promise');

const app = new Koa();

app.use(Riviere.middleware());
app.use(async function(ctx) {
  await rp({
    uri: 'https://www.google.com',
    // You can include the X-Riviere-Id header
    // to trace the request's context inside which
    // the external request is made
    // This is optional but recommended for better tracing:
    headers: {
      'X-Riviere-Id': ctx.request.headers['x-riviere-id'] // notice that this is lowercase
    }
  });
  ctx.body = 'Hello World';
});

app.listen(3000);

Configuration

The behavior of the riviere middleware can be configured by passing a configuration object, as argument to the Riviere.middleware() method call.

You can start using riviere' by just calling app.use(Riviere.middleware()). In this case the riviere will use its default configuration.

The default configuration object is the following:

const riviereConfObj = {
    context: ctx => {
        return {};
    },
    errors: {
        enabled: true,
        callback: (ctx, error) => {
            throw(error);
        }
    },
    health: [],
    inbound: {
        enabled: true,
    }
    outbound: {
        enabled: true
    },
    bodyKeys: [],
    headersRegex: new RegExp('^X-.*', 'i'),
    traceHeaderName: 'X-Riviere-Id'
}

Here is an example of a more advanced configuration:

const riviereConfObj = {
    bodyKeys: [
        'education',
        'work_experience'
    ],
    color: true,
    context: (ctx) => {
        return {
            userId: ctx.request.headers['user-id'],
            accountId: ctx.request.headers['account-id']
        };
    },
    errors: {
        enabled: true,
        callback: (ctx, error) => {
            ctx.status = error.status || 500;

            if (ctx.status < 500) {
                ctx.body = {error: error.message};
            } else {
                ctx.body = {error: 'Internal server error'};
            }
        }
    },
    headersRegex: new RegExp('X-.+', 'i'),
    health: [
        {
            path: '/health',
            method: 'GET'
        }
    ],
    outbound: {
        enabled: true
    },
    traceHeaderName: 'X-Request-Id'
};
app.use(Riviere.middleware(riviereConfObj));

The supported key-value options, for the configuration object are described below.


Available options

inbound

inbound.enabled

Enable inbound HTTP traffic logging. Defaults to true.

bodyKeys

This option can be used to log specific values from the JSON body of the inbound POST requests. Defaults to empty Array []. To use this option, the POST request's body should be a valid JSON. Most often this mean that you should register the Koa bodyParser middleware (https://www.npmjs.com/package/body-parser) (or something equivalent), before registering the riviere middleware.

Example:

{
    bodyKeys: [
        'education',
        'work_experience'
    ]
}

color

Log colored log messages. Defaults to: true

Example:

{
    color: true
}

context

The context to be included in every inbound_request and outbound_response log message. Defaults to empty Object: {}.

Example:

{
    context: (ctx) => {
        return {
            userId: ctx.request.headers['user-id'],
            accountId: ctx.request.headers['account-id']
        };
    }
}

errors

errors.enabled

Enable inbound HTTP traffic logs. Defaults to true.

errors.callback

Control how the server handles any unhandled errors inside a request's context. The default is to re-throw the unhandled error.

Example:

{
    errors: {
        callback: (ctx, error) => {
            ctx.status = error.status || 500;

            if (ctx.status < 500) {
                ctx.body = {error: error.message};
            } else {
                ctx.body = {error: 'Internal server error'};
            }
        }
    }
}

headersRegex

Specify a regular expression to match the request headers, that should be included in every inbound_request log message. Defaults to new RegExp('^X-.+', 'i'). All the inbound request's headers starting with "X-" will be logged by default.

Example:

{
    headersRegex: new RegExp('X-.+', 'i')
}

health

Specify your health endpoints in order to log a minimum subset of information, for these inbound_requests. Defaults to []. This may be useful when: You have a load balancer or other system that pings your server at a specific end-point, periodically, to determine the health of your server, and you do not want to log much details regarding these requests.

Example

{
    health: [
        {
            path: '/health',
            method: 'GET'
        }
    ]
}

outbound

outbound.enabled

Enable outbound HTTP traffic logs. Defaults to true.

Example:

{
    outbound: {
        enabled: true
    }
}

traceHeaderName

Theis is a Header key for the request id header. Defaults to: X-Riviere-Id. If you already use a request id header you may need to set this options. For example for Heroku deployments, you most often want to set the riviere traceHeaderName to: X-Request-Id (https://devcenter.heroku.com/articles/http-request-id)

Example:

{
    traceHeaderName: 'X-Request-Id'
}

License

MIT (see LICENCE)