Node.js application Deployment-Log posts __JS

Source: Internet
Author: User

During the development process, running the server through the node App.js command makes it easy to start a Web site. But he has a major flaw is that there is no log function, for developers, the log, especially the error log is extremely important, so it is necessary to implement the log function.

Express supports two modes of operation: Development mode and product model, the former is designed to facilitate debugging, the latter is conducive to deployment. The way to run a server using product mode is simple, just set the NODE_ENV environment variable node_env=production. At this point in the Run node App.js can see:

Express Server listening on port 3000 in production mode

Next, let's implement the access log and error logging features

Express provides an access log middleware that records the access log by simply specifying the stream parameter as an output stream. Open App.js and add the following code at the top:

var fs = require (' FS ');
var accesslogfile = fs.createwritestream (' Access.log ', {flags: ' A '});
var errorlogfile = fs.createwritestream (' Error.log ', {flags: ' A '});


Then add the first line to the App.configure function:

App.use (Express.logger ({stream:accesslogfile}));

As for the error log, you need to implement the error response individually, as follows:

App.configure (' Production ', function () {
  app.error (function (err, req, res, next) {
    var meta = ' [' + new Date () + '] ' + Req.url + ' \ n ';
    Errorlogfile.write (meta + err.stack + ' \ n ');
    Next ();
  });

The function of this code is to register the error response function through App.error, in which errors are written to the error log stream.

Now that you are running the server again, you can see the access log and the error log.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.