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

express-errorlog

v1.1.0

Published

Error handling and logging for Express (4.x)

Downloads

148

Readme

Express Error Log

A very simple logger for Express 4.x, based on the errorlog NPM module.

Install and use

Install as usual with NPM:

npm install --save express-errorlog

Then configure as the last routes of your Express app:

var errorlog = require('express-errorlog');
app.use(errorlog);

// The error handler writing the response
app.use(function(err, req, res, next) {
  res.json(err);
})

The express-errorlog handler will normalize whatever your application passed to the next(...) function and log an error message.

It will then pass the normalized error to the next error handler, which will have the job of rendering the actual response to the client.

The examples below assume that the final error handler will simply send back a JSON of the normalized error (no need to set the status again, express-errorhandler will set that for you already).

Logging and sample JSON responses

In order to trigger log entries, simply use Express' own next(...) function, passing one of the the following types of parameter:

Numbers

app.get('/test', function(req, res, next) {
  next(400); // Simply interrupt with a 400 Bad Request
});

The number will be interpreted as the status code of the response. If the number is less than zero or greater than 599, the response status will be normalized to a 500 Internal Server Error.

The response sent back to the client will contain the following:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
  "status": 400,
  "message": "Bad Request"
}

And the log will written with

2015-03-30T16:45:01.661Z - GET /test (400) - Bad Request

Strings

app.get('/test', function(req, res, next) {
  next("Something is wrong"); // Interrupt with a message
});

The number will be interpreted as the status message for the response, while the status will be defaulted to a 500 Internal Server Error.

The response sent back to the client will contain the following:

HTTP/1.1 500 Internal Server Error
Content-Type: application/json

{
  "status": 500,
  "message": "Something is wrong"
}

And the log will written with

2015-03-30T16:45:01.661Z - GET /test (500) - Something is wrong

Objects

app.get('/test', function(req, res, next) {
  var error = new Error('Invalid access for user');
  error.user = '[email protected]';
  error.token = 'c568019d-3c80-4685-8982-ed455a2c0cd1';

  next({
    status: 403,
    message: 'You have no access, my friend',
    error: error,
    details: {
      example: "... some extra token for the response ..."
    },
  });
});

Objects can also be passed directly to the next(...) call, having the following keys:

  • status: A number representing the status code of the response.
  • message: The message to transmit to the client.
  • error: An Error that will be logged, but not transmitted to the client.
  • details: Anything that will be serialized to JSON and sent back alongside the response.

In the example above, the response will be:

HTTP/1.1 403 Forbidden
Content-Type: application/json

{
  "status": 403,
  "message": "You have no access, my friend",
  "details": {
    "example": "... some extra token for the response ..."
  }
}

And the log will contain something along the following:

2015-03-30T16:45:01.718Z - GET /test (403) - You have no access, my friend
  >>> {"example":"... some extra token for the response ..."}
  >>> {"user":"[email protected]","token":"c568019d-3c80-4685-8982-ed455a2c0cd1"}
  Error: Invalid access for user
    at Error (native)
    at ... stacktrace continues ...

In other words, details and error will be logged and the Error's stack trace will be dumped in full. At the same time, note that there is no trace of the error in the response sent back to the client.

Errors

app.get('/test', function(req, res, next) {
  // Create and instrument an error
  var error = new Error('Something is amiss');
  error.status = 410;
  error.details = {
    example: "... some extra token for the response ..."
  };
  // Equivalent to `next(error);`
  throw error;
});

Whether thrown or passed to next(...), exceptions will produce a 500 Internal Server Error unless they expose a status property directly and their message will be sent alongside the response, as:

HTTP/1.1 410 Gone
Content-Type: application/json

{
  "status": 410,
  "message": "Something is amiss",
  "details": {
    "example": "... some extra token for the response ..."
  }
}

The log will contain the full details and stack trace of the error:

2015-03-30T16:45:01.718Z - GET /test (410) - Something is amiss
  >>> {"example":"... some extra token for the response ..."}
  Error: Something is amiss
    at Error (native)
    at ... stacktrace continues ...

Request IDs

If the Express' request contains the special id value (as for example when using express-request-id) said id will also be reported, for example:

2015-03-30T16:45:01.661Z - d7c32387-3feb-452b-8df1-2d8338b3ea22 - GET /test (500) - Something is wrong

Wrapped logger

The wrapped errorlog instance also available as log(...), for example:

var errorlog = require('express-errorlog');
app.use(errorlog);

// Log something
errorlog.log.info('This is an info message');

Configuration

Configure accepts basically the same options as errorlog:

var errorlog = require('express-errorlog');
app.use(errorlog({
  logger: function/stream,
}));
  • logger may be one of the following:
    • a Writable stream to which error messages will be written to (actually an object offering a write(...) function will do).
    • a simple function that will be invoked once with each message to log.
    • if unspecified this will default to process.stderr.
  • category: a category name that will be inserted in the message to log.

As with errorlog, use a package like logrotate-stream if log rotation is necessary in your environment.

License (MIT)

Copyright (c) 2015 USRZ.com and Pier Paolo Fumagalli

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.