Wednesday, July 3, 2013

baseapp: Administration

baseapp provides all the boilerplate to get your JavaScript web application started off right, this Part 8.

  1. Intro to baseapp
  2. Client-Side Unit Tests
  3. Server-Side Unit Tests
  4. WebDriver Integration Tests
  5. Other Grunt Goodies
  6. Authentication
  7. Continuous Integration
  8. Administration
(or binge read them all on the baseapp wiki!)

Logging

Bunyan provides very flexible JSON-based logging solution. Here is its config:

Bunyan = require('bunyan')
, log = Bunyan.createLogger({
    name: "YOUR_APP"
    , serializers : Bunyan.stdSerializers 
    , streams: [{
        type: 'rotating-file'
        , path: 'logs/http.log'
        , period: '1d'
        , count: 3
    }] 
  })

All server logs are are kept in the 'logs' directory, rolled over every day, and 3 previous logs are kept. Bunyan's standard serializers handle serializing the request and response objects.

The logging routine is here:

app.set('logger', log);

// bunyan logging
app.use(function(req, res, next) {
    var end = res.end;
    req._startTime = new Date();
    res.end = function(chunk, encoding){
        res.end = end;
        res.end(chunk, encoding);
        log.info({req: req, res: res, total_time: new Date() - req._startTime}, 'handled request/response');
    };

    next();
});

This is the second Express 'use' statement - make sure it's near or at the top (only below the 'favicon' use) to log everything! This is taken directly from the 'connect.Logger' middleware - it basically hooks itself into the response 'end' method to record the total time the request took and the request and response objects.

Note we also stash the 'log' object in Express so other middleware can access it.

Starting and Stopping the Server

baseapp uses the awesome forever module to handle the start, restart, and stop of our server. Take a look at our 'start' and 'stop' commands in package.json:

"start": "node_modules/.bin/forever -a -p logs --minUptime 2000 --spinSleepTime 1000 -l forever.log -o logs/out.log -e logs/err.log start app.js",
"stop": "node_modules/.bin/forever stop app.js",

They delegate the handling of starting and stopping our websever to forever - which once started will monitor the process forever (Hmmm) and restart it if it crashes. However our server must be up for at least 2 seconds before forever will try to restart it - remember our server will kill itself off if it cannot connect to 'redis' so in that case we do not want forever always trying to restart it.

The '--spinSleepTime' option just says wait 1 second before trying to start up the server if it died (the forever default). We use the 'append' option (-a) and put all of forever's logs into our 'logs' directory and that's it!.

Executing:

% npm start

Will keep our webserver up even when/if it crashes subject to sane constraints. Plus we have a clean way to stop it via:

% npm stop

The server gets its HOST and PORT values to listen on from the environment. Here are its defaults:

app.set('port', process.env.PORT || 3000);
app.set('host', process.env.HOST || '0.0.0.0');

To change this:

% PORT=9999 HOST=localhost npm start

Now your server is listening on http://localhost:9999 (your shell may vary!). npm config variables is another way to go.

Forever has a couple more tricks up its sleeve - want to know what process forever has spawned off for you - 'forever list' to the rescue:

% node_modules/.bin/forever list
    info:    Forever processes running
    data:        uid  command             script forever pid   logfile          uptime
    data:    [0] OlRc /usr/local/bin/node app.js 54323   54324 logs/forever.log 0:0:0:3.727

You can edit the columns this command displays but you can read the forever documentation for that.

Finally note the index number '[0]' of our process - want to see the 'forever.log' for it but too lazy to load it up yourself? Here ya go:

% node_modules/.bin/forever logs 0
    data:    app.js:54324 - Express server listening on http://0.0.0.0:3000
    data:    app.js:54324 - Express server listening on http://0.0.0.0:9999
    data:    app.js:54324 - Express server listening on http://0.0.0.0:9999
    data:    app.js:54324 - Express server listening on http://localhost:9999
    data:    app.js:54324 - Express server listening on http://0.0.0.0:9999

15 comments:

  1. Stuck with server level programming or networking issues? Getting computer networking assignment help might be helpful.

    ReplyDelete
  2. Thank you so much for sharing this solution, I was facing some issue on my Persuasive Essay Writing Service website server.

    ReplyDelete
  3. its very boring hobby to learn programing my favorite hobby is to watch netflix movies with my all time favorite streaming services StreaMaestro

    ReplyDelete
  4. Thanks for shairng nice post, When you are stressed, your heart beats faster, your blood pressure rises, your breathing gets faster, Psychology Assignment Help and your hands may shake. Your emotions get triggered and you feel more anxious.

    ReplyDelete
  5. Find notable styles to browse, including; cowhide coats, aircraft coats, parkas, and Detroit Become Human Simon Jericho Leather Jacket. Shop different styles including denim coats. Find the selective Men's creator Jackets and Coats assortment by VERSACE. Purchase online the notorious VERSACE items, extravagance and tastefulness models.

    ReplyDelete
  6. It is a nice time surfing from your great adventure blog is a privilege. It is really an insightful piece. Thank you for taking time and effort to put this entire informative article together. Thanks so much for sharing. lasu cut off mark

    ReplyDelete
  7. A server is a computer program or a machine that provides services or resources to other devices or programs, often over a network. Servers are designed to handle client requests and respond with the requested information, data, or functionality. In general, servers are more powerful and have more resources than client devices, and can handle multiple requests simultaneously. Servers can provide a variety of services such as web hosting, email, file sharing, databases, Dissertation Writing Service London and application hosting. They are an essential component of many networks and play a critical role in facilitating communication and data exchange between different devices and systems.




    ReplyDelete
  8. "Random Thoughts O Mine" seems like an engaging platform to share diverse perspectives. Just as thoughts flow freely, I find that delegating academic tasks through do my assignment services allows me to concentrate on grasping intricate concepts. This collaboration ensures quality work and encourages a comprehensive understanding of subjects, much like the array of thoughts shared on the blog. It's a balance between contributing and learning, enriching both realms of knowledge and expression.

    ReplyDelete
  9. My Catalyst 4003/4006r stays up and operating without a hitch thanks to the WS-X4008 Cisco AC Power Supply. It supports the stability of my network. 💪🔌

    ReplyDelete
  10. It's a pleasant time. Surfing from your best football books for coaches is an honor. It's a really insightful piece. Thank you for spending the time and effort to compile this comprehensive information. Thank you very much for sharing.

    ReplyDelete
  11. The relationship betweenold yachts for sale, Silicon Valley, Hungary, and emerging markets has enormous potential for global growth and innovation. They can solve current concerns and drive technical progress by pooling their skills and resources. Such initiatives can substantially benefit students in need of academic assistance, such as university assignment aid, because they can tap into the knowledge and opportunities provided by these collaborations to improve their learning experience and broaden their perspectives.

    ReplyDelete
  12. "Stationery, often overlooked yet indispensable, is the unsung hero of organization in any administrative realm, including Baseapp. Just as a well-stocked desk fosters productivity and efficiency, Baseapp's administration thrives on the foundation of streamlined processes and meticulous attention to detail.

    ReplyDelete
  13. This is the second Express "use" statement; log everything by placing it close to or at the top (just below the "favicon" use, please!). The 'connect.Logger' middleware is directly responsible perfume for men for this; it essentially inserts itself into the response 'end' function to log the entire time the request took as well as the objects for the request and response.

    ReplyDelete