nodejs实现简单http日志存储
/*
日志存储:
202.189.63.115 - - [31/Aug/2008:15:42:31 +0800] "GET / HTTP/1.1" 200 1365 "-"
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1"
*/ let http = require("http"),
fs = require("fs"),
file = "access.log",
retValue = Buffer.from("你好阿"),
date = new Date(),
day = date.getDate(),
month = date.getMonth(),
year = date.getFullYear(),
hours = date.getHours(),
seconds = date.getMinutes(),
milis = date.getSeconds(),
zone = "+8400"; let server = http.createServer(function(req,res){
}).listen(8080) server.on("request",function(req,res){
function getLog(req,status,size){
let rizhi = "",
ip,
time,
method,
page,
protocol,
statusCode,
userAgent;
ip = req.connection.remoteAddress;
time = `[${day}/${month}/${year}:${hours}:${seconds}:${milis} ${zone}]`;
method = req.method;
page = req.url;
protocol = req.httpVersion;
statusCode = status;
size = size;
userAgent = req.headers["user-agent"];
rizhi = `${ip} - - ${time} "${method} ${page} HTTP${protocol}" ${statusCode} ${size}
"-" "${userAgent}"`;
console.log(rizhi)
return rizhi;
}
function writeLog(f,req,res,status,size,fn){
let rizhi = fn(req,status,size);
fs.writeFileSync(file,rizhi)
}
if(req.method.toLowerCase() === 'get'){
if(req.url === '/app'){
let status = 200;
let size = 20000;
writeLog(file,req,res,status,size,getLog)
}
}
})
效果:
::1 - - [9/5/2019:13:54:6 -480] "GET /app HTTP1.1" 200 20000
"-" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"