Node.js - Logging response statusCode to console (a la Django development server)
I'm trying to build a Node.js server with console logging similar to that of Django's development server. E.g.
[27/Jun/2011 15:26:50] "GET /?test=5 HTTP/1.1" 200 545
The following server.js (based on the Node Beginner Book tutorial) gets me the time and request information:
var http = require("http");
var url = require ("url");
var port = 1234;
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
var query = url.parse(request.url).query;
route(handle, pathname, query, response);
logRequest(request);
}
http.createServer(onRequest).listen(port);
console.log("\nServer running at http://192.168.1.5:" + port + "/");
console.log("Press CONTROL-C to quit.\n");
}
function logRequest(request) {
var pathname = url.parse(request.url).pathname;
var query = url.parse(request.url).query;
if (query == undefined) {
query = "";
}
var currentDate = new Date();
var day = currentDate.getDate();
var month = currentDate.getMonth() + 1;
var year = currentDate.getFullYea开发者_如何学Gor();
var hours = currentDate.getHours();
var minutes = currentDate.getMinutes();
var seconds = currentDate.getSeconds();
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
console.log("[" + year + "/" + month + "/" + day +
" " + hours + ":" + minutes + ":" + seconds + '] "' +
request.method + " " + pathname + query +
" HTTP/" + request.httpVersion + '"');
}
exports.start = start;
Question: how would I update this code to get the response.statusCode and whatever the "545" number is into the log output?
When I tried adding the response object to the logRequest function, the response statusCode was always "200", even when I knew (via debug logging) that my router.js was generating 404 errors.
If you are using the route method found in the tutorial you linked, then the reason why using the response.statusCode doesn't work is because they set the 404 status code using this line
response.writeHead(404, {"Content-Type": "text/html"});
If you take a look at the documentation right there Node.JS Docs - writeHead it states that .writeHead will not set the .statusCode value. If you want to use the .statusCode value, you should change the line in the route
method to read like this :
response.statusCode = 404;
response.setHeader("Content-Type", "text/html");
Directly assigning a value to statusCode and using "implicit" header declarations (setHeader instead of writeHead) will produce the same result for the user, but on your side you will have access to the statusCode later on in your log method.
精彩评论