-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
52 lines (43 loc) · 1.22 KB
/
Copy pathserver.js
File metadata and controls
52 lines (43 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const express = require("express");
const morgan = require("morgan");
const fs = require("fs");
const path = require("path");
const rfs = require("rotating-file-stream");
const uuid = require("uuid");
const app = express();
const port = 3000;
// token
morgan.token("id", function getId(req) {
return req.id;
});
app.use((req, res, next) => {
req.id = uuid.v4();
next();
});
app.use(morgan(":id :method :url :response-time"));
// 写日志到单个文件
const accessLogStreamSingle = fs.createWriteStream(
path.join(__dirname, "access.log"),
{ flags: "a" }
);
// 日志文件轮换
const accessLogStreamRotating = rfs.createStream("access.log", {
interval: "1d", // 每天轮换
path: path.join(__dirname, "log"),
});
// 错误响应 输出到控制台
app.use(
morgan("dev", {
skip: function (req, res) {
return res.statusCode < 400;
},
})
);
app.use(morgan("combined", { stream: accessLogStreamSingle })); // dev, combined, common, short, tiny
app.use(morgan("combined", { stream: accessLogStreamRotating })); // dev, combined, common, short, tiny
app.get("/", (req, res) => {
res.send("Hello Express!");
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});