nodejs实现简单http日志存储

 1 /*
 2 日志存储:
 3 202.189.63.115 - - [31/Aug/2008:15:42:31 +0800] "GET / HTTP/1.1" 200 1365 "-"
 4   "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1"
 5 */
 6 
 7 let http = require("http"),
 8     fs = require("fs"),
 9     file = "access.log",
10     retValue = Buffer.from("你好阿"),
11     date = new Date(),
12     day = date.getDate(),
13     month = date.getMonth(),
14     year = date.getFullYear(),
15     hours = date.getHours(),
16     seconds = date.getMinutes(),
17     milis = date.getSeconds(),
18     zone = "+8400";
19 
20 let server  = http.createServer(function(req,res){
21 }).listen(8080)
22 
23 server.on("request",function(req,res){
24     function getLog(req,status,size){
25       let rizhi = "",
26           ip,
27           time,
28           method,
29           page,
30           protocol,
31           statusCode,
32           userAgent;
33       ip = req.connection.remoteAddress;
34       time = `[${day}/${month}/${year}:${hours}:${seconds}:${milis} ${zone}]`;
35       method = req.method;
36       page = req.url;
37       protocol = req.httpVersion;
38       statusCode = status;
39       size = size;
40       userAgent = req.headers["user-agent"];
41       rizhi = `${ip} - - ${time} "${method} ${page} HTTP${protocol}" ${statusCode} ${size}
42         "-" "${userAgent}"`;
43           console.log(rizhi)
44         return rizhi;
45     }
46     function writeLog(f,req,res,status,size,fn){
47         let rizhi = fn(req,status,size);
48         fs.writeFileSync(file,rizhi)
49     }
50     if(req.method.toLowerCase() === 'get'){
51       if(req.url === '/app'){
52           let status = 200;
53           let size = 20000;
54           writeLog(file,req,res,status,size,getLog)
55       }
56     }
57 })
View Code

 

效果:

1 ::1 - - [9/5/2019:13:54:6 -480] "GET /app HTTP1.1" 200 20000
2         "-" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"
View Code