• Stars
    star
    108
  • Rank 321,259 (Top 7 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 10 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Koa middleware for bunyan request logging

bunyan-logger

Update: Koa team member @niftylettuce released a logging package alternative at https://cabinjs.com!

NOTE: that you're reading the README of the version which targets Koa v2.x, if you want to read about the old 1.X version, switch to Tag 1.3.0.

Flexible log context and request logging middleware for koa using bunyan.

Inspired by koa-bunyan, koa-json-logger, bunyan-request, and others.

Build Status Coverage Status npm

A primary goal of this module is to be as flexible as possible, while remaining relatively lightweight, leaving advanced functionality and customization the app.

const koa = require('koa');
const koaBunyanLogger = require('koa-bunyan-logger');

const app = koa();
app.use(koaBunyanLogger());

app.use(function (ctx, next) {
  ctx.log.info('Got a request from %s for %s', ctx.request.ip, ctx.path);
  return next();
});

app.listen(8000);

Server:

node examples/simple.js | ./node_modules/.bin/bunyan -o short`

Client:

curl http://localhost:8000/

Server output:

07:50:14.014Z  INFO koa: Got a request from ::1 for /

Request logging

app.use(koaBunyanLogger());
app.use(koaBunyanLogger.requestIdContext());
app.use(koaBunyanLogger.requestLogger());

Server:

node examples/requests.js | ./node_modules/.bin/bunyan -o short

Client:

curl -H "X-Request-Id: 1234" http://localhost:8000/

Server output:

20:19:24.526Z  INFO koa:   --> GET / (req_id=1234)
    GET / HTTP/1.1
    --
    req.header: {
      "user-agent": "curl/7.30.0",
      "host": "localhost:8000",
      "accept": "*/*",
      "x-request-id": "1234"
    }
20:19:24.527Z  INFO koa:   <-- GET / 1ms (req_id=1234, duration=1, res.status=200, res.message=OK)
    GET / HTTP/1.1
    --
    x-powered-by: koa
    content-type: text/plain; charset=utf-8
    content-length: 11
    --
    req.header: {
      "user-agent": "curl/7.30.0",
      "host": "localhost:8000",
      "accept": "*/*",
      "x-request-id": "1234"
    }

Ignoring specific path from logging

It is possible to skip logs from some endpoints with ignorePath option.

app.use(koaBunyanLogger.requestLogger({ ignorePath: ['/ping'] }))

Suppressing default error stack traces

To ensure that stack traces from request handling don't get logged in their raw non-JSON forms, you can disable the app's default error handler:

app.on('error', function () {});

API Reference

koaBunyanLogger(logger)

Parameters:

  • logger: bunyan logger instance or an object to pass to bunyan.createLogger()

Examples

Use an existing logger:

const bunyan = require('bunyan');
const koaBunyanLogger = require('koa-bunyan-logger');

const appLogger = bunyan.createLogger({
  name: 'myapp',
  level: 'debug',
  serializers: bunyan.stdSerializers
});

app.use(koaBunyanLogger(appLogger));

Shortcut to create a new logger:

const koaBunyanLogger = require('koa-bunyan-logger');

app.use(koaBunyanLogger({
  name: 'myapp',
  level: 'debug'
}));

koaBunyanLogger.requestLogger(opts)

Options:

  • durationField: Name of field to store request duration in ms

  • levelFn: Function which will be called with (status, err) and should return the name of a log level to be used for the response log entry. The default function will log status 400-499 as warn, 500+ as error, and all other responses as info.

  • updateLogFields: Function which will be called with a single argument, an object containing the fields (req, res, err) to be logged with the request and response message.

    The function has the opportunity to add or remove fields from the object, or return a different object to replace the default set of fields. The function will be called using the koa 'this' context, once for the request and again for the response.

  • updateRequestLogFields: Function which will be called with a request fields object when logging a request, after processing updateLogFields.

  • updateResponseLogFields: Function which will be called with a response fields object when logging a response, after processing updateLogFields. It also receives a second argument, err, if an error was thrown.

  • formatRequestMessage: Function which will be called to generate a log message for logging requests. The function will be called in the context of the koa 'this' context and passed the request fields object. It should return a string.

  • formatResponseMessage: Same as formatRequestLog, but for responses.

Examples

Basic usage:

app.use(koaBunyanLogger());
app.use(koaBunyanLogger.requestLogger());

Add custom fields to include in request and response logs:

app.use(koaBunyanLogger.requestLogger({
  // Custom fields for both request and response
  updateLogFields: function (fields) {
    fields.authorized_user = this.user.id;
    fields.client_version = this.request.get('X-Client-Version');
  },

  // Custom fields for response only
  updateResponseLogFields: function (fields, err) {
    if (err) {
      fields.last_db_query = this.db.lastDbQuery();
    }
  }
}));

koaBunyanLogger.requestIdContext(opts)

Get X-Request-Id header, or if the header does not exist, generates a random unique id for each request.

Options:

  • header: name of header to get request id from
  • prop: property to store on context; defaults to 'reqId' e.g. this.reqId
  • requestProp: property to store on request; defaults to 'reqId' e.g. this.request.reqId
  • field: field to add to log messages in downstream middleware and handlers; defaults to 'req_id'

Examples

const koaBunyanLogger = require('koa-bunyan-logger');

app.use(koaBunyanLogger());
app.use(koaBunyanLogger.requestIdContext());

Or use a different header:

const koaBunyanLogger = require('koa-bunyan-logger');

app.use(koaBunyanLogger());
app.use(koaBunyanLogger.requestIdContext({
  header: 'Request-Id'
}));

By default, the request id will be accessible as this.reqId and this.request.reqId:

const koaBunyanLogger = require('koa-bunyan-logger');

app.use(koaBunyanLogger());
app.use(koaBunyanLogger.requestIdContext());

app.use(function (ctx) {
  ctx.response.set('X-Server-Request-Id', ctx.reqId);
  ctx.body = "Hello world";
});

koaBunyanLogger.timeContext(opts)

Adds time(label) and timeEnd(label) methods to the koa context, which records the time between the time() and timeEnd() calls for a given label.

Calls to time() and timeEnd() can be nested or interleaved as long as they're balanced for each label.

Options:

  • logLevel: name of log level to use; defaults to 'trace'
  • updateLogFields: function which will be called with arguments (fields) in koa context; can update fields or return a new object.

Examples

const koaBunyanLogger = require('koa-bunyan-logger');

app.use(koaBunyanLogger());
app.use(koaBunyanLogger.requestIdContext());
app.use(koaBunyanLogger.timeContext());

app.use(function (ctx) {
  ctx.time('get data');

  return getUser()
  .then(u => {
    return getFriend(u)
    .then(f => [u, f]);
  })
  .then(data => {
    let user = data[0];
    let friends = data[1];

    ctx.timeEnd('get data');
    ctx.time('serialize');
    ctx.body = serialize(user, friends);
    ctx.timeEnd('serialize');
  });
});

The same but using async functions

const koaBunyanLogger = require('koa-bunyan-logger');

app.use(koaBunyanLogger());
app.use(koaBunyanLogger.requestIdContext());
app.use(koaBunyanLogger.timeContext());

app.use(async function (ctx) {
  ctx.time('get data');
  let user = await getUser();
  let friends = await getFriend(user);
  ctx.timeEnd('get data');

  ctx.time('serialize');
  ctx.body = serialize(user, friends);
  ctx.timeEnd('serialize');
});

Example output:

{"name":"koa","hostname":"localhost","pid":9228,"level":10,"label":"get data","duration":102,"msg":"","time":"2014-11-07T01:45:53.711Z","v":0}
{"name":"koa","hostname":"localhost","pid":9228,"level":10,"label":"serialize","duration":401,"msg":"","time":"2014-11-07T01:45:54.116Z","v":0}

To return different fields, such as nesting the data under a single field, add a updateLogFields function to the options:

const koaBunyanLogger = require('koa-bunyan-logger');

app.use(koaBunyanLogger());
app.use(koaBunyanLogger.requestIdContext());
app.use(koaBunyanLogger.timeContext({
  updateLogFields: function (fields) {
    return {
      request_trace: {
        name: fields.label,
        time: fields.duration
      }
    };
  }
}));

bunyan export

The internal copy of bunyan is exported as .bunyan:

const koaBunyanLogger = require('koa-bunyan-logger');
const bunyan = koaBunyanLogger.bunyan;

Sponsored by

Pebble Technology!

License

MIT

More Repositories

1

koa

Expressive middleware for node.js using ES2017 async functions
JavaScript
34,326
star
2

examples

Example Koa apps
JavaScript
4,471
star
3

jwt

Koa middleware for validating JSON Web Tokens
JavaScript
1,333
star
4

bodyparser

Koa body parsing middleware
TypeScript
1,273
star
5

static

Static file server middleware
JavaScript
1,124
star
6

compose

Middleware composition utility
JavaScript
986
star
7

koa-body

koa body parser middleware
TypeScript
923
star
8

session

Simple session middleware for koa
JavaScript
902
star
9

router

Router middleware for Koa. Maintained by @forwardemail and @ladjs.
JavaScript
790
star
10

cors

Cross-Origin Resource Sharing(CORS) for koa
JavaScript
723
star
11

kick-off-koa

[MAINTAINERS WANTED] An intro to koa via a set of self-guided workshops
JavaScript
693
star
12

logger

Development style logging middleware
JavaScript
561
star
13

mount

Mount other Koa applications or middleware to a given pathname
JavaScript
549
star
14

ratelimit

Rate limiter middleware
JavaScript
466
star
15

joi-router

Configurable, input and output validated routing for koa
JavaScript
450
star
16

route

Simple route middleware
JavaScript
442
star
17

workshop

Koa Training Workshop
JavaScript
436
star
18

compress

Compress middleware for koa
JavaScript
432
star
19

koa.io

[MAINTAINERS WANTED] Realtime web framework combine koa and socket.io.
JavaScript
427
star
20

send

Transfer static files
TypeScript
420
star
21

generic-session

koa session store with memory, redis or others.
JavaScript
414
star
22

koa-redis

Redis storage for Koa session middleware/cache with Sentinel and Cluster support
JavaScript
352
star
23

koala

[SEEKING MAINTAINER] An HTTP/2 and ES6 Module-ready Koa Suite
JavaScript
320
star
24

static-cache

[MAINTAINERS WANTED] Static cache for koa
JavaScript
293
star
25

csrf

CSRF tokens for koa
JavaScript
265
star
26

react-view

A Koa view engine which renders React components on server
JavaScript
256
star
27

convert

Convert koa generator-based middleware to promise-based middleware
JavaScript
254
star
28

ejs

a koa view render middleware, support all feature of ejs
JavaScript
248
star
29

json

pretty-printed JSON response middleware
JavaScript
197
star
30

todo

a todo example write with koa and react
JavaScript
165
star
31

koa-hbs

Handlebars templates for Koa.js
JavaScript
159
star
32

cash

HTTP response caching for Koa. Supports Redis, in-memory store, and more!
JavaScript
154
star
33

onerror

an error handler for koa, hack ctx.onerror
JavaScript
139
star
34

basic-auth

blanket basic auth middleware
JavaScript
138
star
35

userauth

koa user auth middleware
JavaScript
137
star
36

multer

Middleware for handling `multipart/form-data` for koa, based on Express's multer.
JavaScript
137
star
37

response-time

X-Response-Time middleware
JavaScript
124
star
38

trie-router

Trie-routing for Koa
JavaScript
122
star
39

koa-roles

koa version of Connect-Roles
JavaScript
117
star
40

etag

ETag support for Koa responses
JavaScript
112
star
41

favicon

Koa middleware for serving a favicon
JavaScript
104
star
42

error

Error response middleware (text, json, html)
JavaScript
103
star
43

rewrite

URL rewriting middleware
JavaScript
100
star
44

json-filter

Middleware allowing the client to filter the response to only what they need, reducing the amount of traffic over the wire.
JavaScript
92
star
45

json-error

Error handler for pure-JSON apps
JavaScript
89
star
46

qs

qs for koa, and use querystring more safely.
JavaScript
85
star
47

bigpipe-example

[DEPRECATED] BigPipe using koa and component
JavaScript
83
star
48

common

[DEPRECATED] USE INDIVIDUAL MODULES
JavaScript
77
star
49

locales

koa locales, i18n solution for koa
JavaScript
67
star
50

koa-lusca

koa version of lusca. Application security for koa.
JavaScript
65
star
51

cluster

Koa clustering and error handling utility
JavaScript
64
star
52

parameter

parameter validate middleware for koa, powered by parameter
JavaScript
62
star
53

conditional-get

Conditional GET middleware for koa
JavaScript
59
star
54

trace

generic tracing for koa
JavaScript
53
star
55

koa-range

[MAINTAINERS WANTED] range request implementation for koa, see http://tools.ietf.org/html/rfc7233
JavaScript
47
star
56

sendfile

basic file-sending utility for koa
JavaScript
45
star
57

koajs.com

The koajs.com website
HTML
42
star
58

mock

Simple web page mock middleware
JavaScript
40
star
59

body-parsers

collection of koa body parsers
JavaScript
37
star
60

koa-markdown

Auto convert markdown to html for koa. Inspired by connect-markdown
JavaScript
37
star
61

koa-gzip

[Deprecated] please use koa-compress instead
JavaScript
36
star
62

file-server

file serving middleware for koa
JavaScript
36
star
63

bundle

Generic asset pipeline with caching, etags, minification, gzipping and sourcemaps.
JavaScript
36
star
64

resourcer

A simple resource directory mounter for koa.
JavaScript
34
star
65

path-match

koa route middleware
JavaScript
33
star
66

html-minifier

minify HTML responses like some crazy guy
JavaScript
31
star
67

webcam-mjpeg-stream

[DEPRECATED] Stream JPEG snapshots from your Mac
JavaScript
28
star
68

timer

time your middleware
JavaScript
26
star
69

statsd

Statsd middleware
JavaScript
24
star
70

redis-session-sets

Koa Redis sessions with field-referencing cross sets
JavaScript
20
star
71

accesslog

Middleware for common log format access logs
JavaScript
19
star
72

is-json

check if a koa body should be interpreted as JSON
JavaScript
17
star
73

charset

use iconv-lite to encode the body and set charset to content-type
JavaScript
16
star
74

koa-safe-jsonp

Safe jsonp plusins for koa.
JavaScript
16
star
75

trace-influxdb

InfluxDB tracing for koa-trace
JavaScript
15
star
76

stateless-csrf

CSRF without sessions.
JavaScript
15
star
77

atomic-session

DEPRECATED
JavaScript
15
star
78

cross-cookies

Easily set cookies across subdomains
JavaScript
13
star
79

koa-github

simple github auth middleware for koa
JavaScript
13
star
80

s3-cache

Koa middleware to cache and serve from S3
JavaScript
11
star
81

eslint-config-koa

Koa's ESLint config, based on Standard
JavaScript
11
star
82

ctx-cache-control

Augment Koa with ctx.cacheControl(maxAge)
JavaScript
9
star
83

snapshot

take snapshot when request, cache by request path.
JavaScript
9
star
84

compressor

[DEPRECATED] Compress middleware for koa that always compresses
JavaScript
9
star
85

koa-fresh

DEPRECATED
JavaScript
8
star
86

cdn

[DEPRECATED] middleware for a koa-based CDN
JavaScript
7
star
87

koa-rt

koa rt with microtime
JavaScript
6
star
88

override-method

method override utility for koa
JavaScript
6
star
89

ctx-basic-auth

Augments Koa with ctx.basicAuth
JavaScript
5
star
90

resourcer-docs

[MAINTAINERS WANTED] Simple app that generates documentation for routes mounted using koa-resourcer.
JavaScript
5
star
91

middleware-hook

low-level hooks for your middleware
JavaScript
5
star
92

path

[DEPRECATED] path-matching middleware for koa
JavaScript
4
star
93

observable-redis-session

[DEPRECATED] Observable, atomic sessions for Koa using Redis
JavaScript
2
star
94

help

koa(1) executable for instant help
2
star
95

discussions

KoaJS Discussions
1
star