nodejs常用的日志系统跟java类似可以使用log4js日志系统
log4js 日志系统的等级从低到高的顺序是:trace、debug、info、warn、error、fatal 我们设置的level值只要输出信息高于level值都会输出,低于我们设置的level值的时候不会输出到对应文件中,本例是设置的最低level值这样所有的信息都会输出到对应日志文件中了,具体项目看情况设定就行了
const express = require("express");
const log4js = require("log4js");
const app = express();
const path = require("path");
const bodyParser = require("body-parser");
const fs = require("fs");
const router = require("./routes/Router.js");
console.log("__dirname is ",__dirname);
log4js.configure({
appenders: {
cheese: {
type: "dateFile",
filename: "logs/cheese",
pattern: "-yyyy-MM-dd.log",
alwaysIncludePattern: true,
category: "normal",
maxLogSize: 1024 * 12,
}
},
categories: {
default: {
appenders: ["cheese"],
/**
* 高于我们自己设置的都会输出到对应文件中去
*/
level: "trace"
}
}
})
// app.use(log4js.connectLogger(log4js.getLogger("cheese"),{level: log4js.levels.INFO}))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
// app.use(express.static(path.join(__dirname,"public")));
app.all("*",(req,res,next) => {
// console.log("all response is ",response);
res.header("Access-Control-Allow-Origin","*");
res.header("Access-Control-Allow-Headers","content-type");
//跨域允许的请求方式
res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
if (req.method.toLowerCase() == 'options')
res.send(200); //让options尝试请求快速结束
else
next();
})
const loggerCheese = log4js.getLogger("normal");
app.get('/test',(req,res) => {
loggerCheese.info("test 接口获得的参数信息是:",req.body);
loggerCheese.info("test接口",req.body);
// logger.level = "info";
console.log("body is ",req.body);
console.log("req's params is ",req.params);
fs.stat(__dirname + "/public/images",(err,data) => {
if(err) {
return;
}
});
fs.readFile(__dirname + "/public/images/ps.png",function(err,data) {
if(err) {
console.log("读取文件失败");
return;
}
// console.log("data is ",data);
let dataText = data.toString("utf-8");
// console.log("dataText is ",dataText);
// 复制文件
let rs = fs.createReadStream(__dirname + "/public/images/ps.png");
let ts = fs.createWriteStream(__dirname + "/public/images/psc.png");
rs.pipe(ts);
res.end(data);
})
// res.end("hello world");
});
// 获得奖励接口
app.post("/getAward",(req,res) => {
// logger.level = "debug";
loggerCheese.debug("getAward接口接收的参数是:req is ",req.body);
loggerCheese.info("---------获得奖励的接口开始------------");
// loggerCheese.warn("该接口已经将要废弃,请使用最新的接口");
loggerCheese.trace("router is ",req.path);
// logger.
let data = {
num : 0,
status : 200,
message: "ok",
};
let body = req.body;
console.log("body is ",body);
let num = router.backAward();
data.num = num;
// res.sendStatus(200);
res.send(data);
loggerCheese.info("---------获得奖励的接口结束------------");
})
app.listen(3001,()=> {
console.log("example app listeing on port 3000");
console.log("I have been start a serve on port 3000");
})