Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to log every request in the console with restify?

I'm using restify to build an API, and I'm used to express. Is there a way to have restify log every request in the console, like express does with app.use(express.logger('dev'))?

like image 709
Samuel Bolduc Avatar asked Dec 17 '13 05:12

Samuel Bolduc


People also ask

What is Restify in NPM?

restify optimizes for introspection and performance, and is used in some of the largest Node. js deployments on Earth.

What is the use of Restify?

Restify is a framework built specifically to build REST web services in Node. js frameworks such as Express. js and Hapi. Restify manages such difficult tasks as versioning, error handling, and content negotiation.


1 Answers

Here is a very bare bones Restify/Bunyan example that will log every request:

'use strict';

var Logger = require('bunyan'),
    restify = require('restify'),
    log = new Logger.createLogger({
        name: 'app-name',
        serializers: {
            req: Logger.stdSerializers.req
        }
    }),
    server = restify.createServer({
        name: 'app-name',
        version: '0.1.0',
        log: log
    });

server.pre(function (request, response, next) {
    request.log.info({ req: request }, 'REQUEST');
    next();
});

server.get('/', function (request, response, next) {
    response.send('It worked!');
    next();
});

server.listen(8080, function () {
    console.log('%s listening at %s', server.name, server.url);
});

The key to this is the server.pre() call.

Start it up in one terminal window and do a curl request in another terminal window. You will see the response that it worked, and a log entry for the request.

Assuming a few things:

  • You have a package.json file that will install bunyan and restify
  • You put the code above in a file named server.js

You would do/see the following:

Terminal Window 1

$ node server.js
app-name listening at http://0.0.0.0:8080
{"name":"app-name","hostname":"leeloo.local","pid":97387,"level":30,"req":{"method":"GET","url":"/","headers":{"user-agent":"curl/7.30.0","host":"localhost:8080","accept":"*/*"},"remoteAddress":"127.0.0.1","remotePort":60870},"msg":"REQUEST","time":"2014-04-21T17:55:52.487Z","v":0}

Terminal Window 2

$ curl localhost:8080/
"It worked!"

If anyone would like to see my package.json I can put all of this up in a gist.

like image 184
jamie young Avatar answered Oct 11 '22 13:10

jamie young