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.