Skip to content

Commit

Permalink
使用winston管理日志
Browse files Browse the repository at this point in the history
  • Loading branch information
SunWuyuan committed Nov 24, 2024
1 parent 905a312 commit 183ad00
Show file tree
Hide file tree
Showing 24 changed files with 91 additions and 73 deletions.
9 changes: 4 additions & 5 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,10 @@ var app = express();
const jwt = require("jsonwebtoken");

const configManager = require("./server/configManager.js");
const logger = require("./server/logger.js");
const logger = require("./server/lib/logger.js");

require("dotenv").config({ override: true });



expressWinston = require("express-winston");

app.use(
Expand Down Expand Up @@ -199,15 +197,16 @@ app.get("/check", function (req, res, next) {
message: "success",
code: 200,
});
logger.debug("check");});
logger.debug("check");
});

process.on("uncaughtException", function (err) {
logger.error("Caught exception: " + err);
});

// Centralized error-handling middleware function
app.use((err, req, res, next) => {
logger.error(err.stack);
logger.error(err);
res.status(500).send({
status: "error",
message: "Something went wrong!",
Expand Down
2 changes: 1 addition & 1 deletion server/configManager.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const logger = require("./lib/logger.js");
const { PrismaClient } = require("@prisma/client");
const logger = require("./logger");

class ConfigManager {
constructor() {
Expand Down
5 changes: 3 additions & 2 deletions server/lib/captcha/captcha.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const logger = require("../logger.js");
const configManager = require("../configManager");

const express = require("express");
Expand All @@ -20,12 +21,12 @@ app.use(async (req, res, next) => {
},
function (error, httpResponse, body) {
if (error) {
console.error("Error verifying recaptcha:", error);
logger.error("Error verifying recaptcha:", error);
res.status(200).send({ message: "验证码验证失败", error: error });
}

const response = JSON.parse(body);
console.log(response);
logger.debug(response);
if (response.success) {
next();
} else {
Expand Down
15 changes: 8 additions & 7 deletions server/lib/captcha/geetest.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const logger = require("../logger.js");
const configManager = require("../../configManager");

const express = require("express");
Expand All @@ -23,7 +24,7 @@ app.use(async (req, res, next) => {

// 处理验证码信息
try {
console.log(req.body.captcha);
logger.debug(req.body.captcha);
if (req.body.captcha) {
// 如果是字符串则转为json
if (typeof req.body.captcha === "string") {
Expand All @@ -38,12 +39,12 @@ app.use(async (req, res, next) => {
: querystring.parse(req.url.split("?")[1]) || req.body;
}
} catch (error) {
console.error("Captcha Parsing Error:", error);
logger.error("Captcha Parsing Error:", error);
res.status(400).send({ code: 400, msg: "Invalid captcha data" });
return;
}

console.log(geetest);
logger.debug(geetest);

// 生成签名
const sign_token = hmac_sha256_encode(geetest.lot_number, GEE_CAPTCHA_KEY);
Expand All @@ -64,15 +65,15 @@ app.use(async (req, res, next) => {
if (result.result === "success") {
next(); // 验证成功,继续处理请求
} else {
console.log(`Validate fail: ${result.reason}`);
logger.debug(`Validate fail: ${result.reason}`);
res.status(500).send({
code: 500,
msg: `请完成验证码/${result.reason}`,
status: `请完成验证码/${result.reason}`,
});
}
} catch (error) {
console.error("Geetest server error:", error);
logger.error("Geetest server error:", error);
next(); // 极验服务器出错时放行,避免阻塞业务逻辑
}
});
Expand All @@ -91,12 +92,12 @@ async function post_form(datas, url) {
});

if (response.status !== 200) {
console.error(`Geetest Response Error, StatusCode: ${response.status}`);
logger.error(`Geetest Response Error, StatusCode: ${response.status}`);
throw new Error("Geetest Response Error");
}
return response.data;
} catch (error) {
console.error("Request to Geetest failed:", error);
logger.error("Request to Geetest failed:", error);
throw error;
}
}
Expand Down
9 changes: 5 additions & 4 deletions server/lib/database.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,34 @@
const logger = require("./logger.js");
// 连接MySQL
var mysql = require("mysql");
var pool = mysql.createPool(process.env.DATABASE_URL);

//防止注入:'SELECT * FROM ow_users WHERE ?', WHERE
exports.qww = function query_with_w(SQL, W, callback) {
pool.getConnection(function (err, connection) {
//console.log(err)
//logger.debug(err)
if (err) return callback(err, "");

// Use the connection
connection.query(SQL, W, function (err, rows) {
callback(err, rows);
connection.release(); //释放链接
console.log(SQL);
logger.debug(SQL);
});
});
};

//正常操作
exports.query = function query(SQL, callback) {
pool.getConnection(function (err, connection) {
//console.log(err)
//logger.debug(err)
if (err) return callback(err, "");

// Use the connection
connection.query(SQL, function (err, rows) {
callback(err, rows);
connection.release(); //释放链接
console.log(SQL);
logger.debug(SQL);
});
});
};
Expand Down
2 changes: 1 addition & 1 deletion server/lib/global.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const configManager = require("../configManager");
const logger = require("../logger");
const logger = require("./logger");

const crypto = require("crypto");
const jwt = require("jsonwebtoken"); // 确保安装了 jsonwebtoken 库
Expand Down
File renamed without changes.
3 changes: 2 additions & 1 deletion server/lib/method/projectlist.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const logger = require("../logger.js");
const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();
const { getProjectsAndUsersByProjectsList } = require("./projects.js");
Expand All @@ -14,7 +15,7 @@ function cleanAndDeduplicateList(list) {

// 统一的错误处理函数
function handleError(error) {
console.error(error);
logger.error(error);
throw new Error(error.message || "发生了错误");
}

Expand Down
9 changes: 5 additions & 4 deletions server/lib/method/projects.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const logger = require("../logger.js");
//prisma client
const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();
Expand Down Expand Up @@ -26,11 +27,11 @@ async function getProjectsByList(list, userid) {
select: select,
});

//console.log(projects);
//logger.debug(projects);
projects = projects.filter((project) => {
return !(project.state == "private" && project.authorid != userid);
});
//console.log(projects);
//logger.debug(projects);

return projects;
}
Expand All @@ -40,9 +41,9 @@ async function getProjectsAndUsersByProjectsList(list, userid) {
var users = await getUsersByList(userslist);
return { projects: projects, users: users };
}
//(async () => {console.log(await getProjectsAndUsersByProjectsList([3, 126, 130, 131, 129], 2));})();
//(async () => {logger.debug(await getProjectsAndUsersByProjectsList([3, 126, 130, 131, 129], 2));})();

//console.log(await getProjectsAndUsersByProjectsList([3, 126, 130, 131, 129], 2))
//logger.debug(await getProjectsAndUsersByProjectsList([3, 126, 130, 131, 129], 2))
module.exports = {
getProjectsByList,
getUsersByList,
Expand Down
3 changes: 2 additions & 1 deletion server/lib/method/users.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
//prisma client
const logger = require("../logger.js");
const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();

Expand All @@ -21,7 +22,7 @@ async function getUsersByList(list) {
select: select,
});

//console.log(users);
//logger.debug(users);

return users;
}
Expand Down
5 changes: 3 additions & 2 deletions server/lib/totpUtils.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const logger = require("./logger.js");
const OTPAuth = require("otpauth");
const I = require("./global.js");

Expand Down Expand Up @@ -203,7 +204,7 @@ async function validateTotpToken(req, res, next) {
req.query.totp_token ||
req.body.totp_token ||
req.headers["x-totp-token"];
console.log(token);
logger.debug(token);
if (!res.locals.login) {
// 未登录,返回401 Unauthorized状态码
return res.status(401).send({ status: "0", msg: "请先登录以继续操作" });
Expand Down Expand Up @@ -231,7 +232,7 @@ async function validateTotpToken(req, res, next) {
// If valid, move to the next middleware or route handler
next();
} catch (error) {
console.error("Error in TOTP validation middleware:", error);
logger.error("Error in TOTP validation middleware:", error);
return res.status(500).json({
status: "error",
message: "Internal server error during TOTP validation.",
Expand Down
1 change: 1 addition & 0 deletions server/middleware/auth.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const logger = require("../lib/logger.js");
const configManager = require("../configManager");

async function needlogin(req, res, next) {
Expand Down
25 changes: 13 additions & 12 deletions server/router_account.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const logger = require("./lib/logger.js");
const configManager = require("./configManager");

var express = require("express");
Expand Down Expand Up @@ -25,11 +26,11 @@ router.all("*", function (req, res, next) {
/*
(async () => {
try {
console.log("site.name:", await configManager.getConfig("site.name"));
logger.debug("site.name:", await configManager.getConfig("site.name"));
// 其他逻辑...
} catch (error) {
console.error("Error:", error);
logger.error("Error:", error);
}
})();
*/
Expand Down Expand Up @@ -101,7 +102,7 @@ router.post("/login", async function (req, res, next) {
display_name: User["display_name"],
avatar: User["images"],
});
//console.log(token);
//logger.debug(token);
// res.cookie("token", token, { maxAge: 604800000 });
res.status(200).send({
status: "OK",
Expand Down Expand Up @@ -155,7 +156,7 @@ router.post("/register", geetest, async function (req, res, next) {
var INSERT = `INSERT INTO ow_users (username,email,password,display_name) VALUES ('${Date.now()}','${email}','${pw}','${display_name}')`;
DB.query(INSERT, async function (err, newUser) {
if (err) {
console.error(err);
logger.error(err);
res.status(200).send({ message: "再试一次17" });
return;
}
Expand Down Expand Up @@ -265,7 +266,7 @@ router.get("/totp/list", needlogin, async (req, res) => {
},
});
} catch (error) {
console.error("获取验证器列表时出错:", error);
logger.error("获取验证器列表时出错:", error);
return res.status(500).json({
status: "error",
message: "获取验证器列表失败",
Expand Down Expand Up @@ -299,7 +300,7 @@ router.post("/totp/rename", needlogin, async (req, res) => {
data: renamedTotp,
});
} catch (error) {
console.error("重命名验证器时出错:", error);
logger.error("重命名验证器时出错:", error);
return res.status(500).json({
status: "error",
message: "重命名验证器失败",
Expand All @@ -324,7 +325,7 @@ router.post("/totp/check", async (req, res) => {
data: { validated: isValid },
});
} catch (error) {
console.error("验证令牌时出错:", error);
logger.error("验证令牌时出错:", error);
return res.status(500).json({
status: "error",
message: "验证令牌失败",
Expand All @@ -348,7 +349,7 @@ router.post("/totp/delete", needlogin, async (req, res) => {
data: deletedTotp,
});
} catch (error) {
console.error("删除验证器时出错:", error);
logger.error("删除验证器时出错:", error);
return res.status(500).json({
status: "error",
message: "删除验证器失败",
Expand All @@ -365,7 +366,7 @@ router.post("/totp/generate", needlogin, async (req, res) => {
data: info,
});
} catch (error) {
console.error("创建验证器时出错:", error);
logger.error("创建验证器时出错:", error);
return res.status(500).json({
status: "error",
message: "创建验证器失败",
Expand Down Expand Up @@ -396,7 +397,7 @@ router.post("/totp/activate", needlogin, async (req, res) => {
data: activatedTotp,
});
} catch (error) {
console.error("激活验证器时出错:", error);
logger.error("激活验证器时出错:", error);
return res.status(500).json({
status: "error",
message: "激活验证器失败",
Expand Down Expand Up @@ -448,7 +449,7 @@ router.post("/magiclink/generate", geetest, async (req, res) => {

res.status(200).json({status: "success", message: "Magic Link 已发送到您的邮箱" });
} catch (error) {
console.error("生成 Magic Link 时出错:", error);
logger.error("生成 Magic Link 时出错:", error);
res.status(200).json({ status: "error", message: "生成 Magic Link 失败" });
}
});
Expand Down Expand Up @@ -496,7 +497,7 @@ router.get("/magiclink/validate", async (req, res) => {
token: jwtToken,
});
} catch (error) {
//console.error("验证 Magic Link 时出错:", error);
//logger.error("验证 Magic Link 时出错:", error);
res.status(200).json({ status: "error",message: "验证 Magic Link 失败" });
}
});
Expand Down
3 changes: 2 additions & 1 deletion server/router_api.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const logger = require("./lib/logger.js");
const configManager = require("./configManager");

var express = require("express");
Expand Down Expand Up @@ -62,7 +63,7 @@ router.get("/getuserinfo", async function (req, res, next) {
},
});
if (!user[0]) {
console.log("用户不存在");
logger.debug("用户不存在");
res.locals.tip = { opt: "flash", msg: "用户不存在" };
res.status(404).json({
status: "error",
Expand Down
Loading

0 comments on commit 183ad00

Please sign in to comment.