gpt4 book ai didi

javascript - 如何将 winston 日志文件保存到 mysql 数据库中?

转载 作者:行者123 更新时间:2023-12-05 04:25:32 25 4
gpt4 key购买 nike

我已经像这样配置了 winston 记录器:

import winston from "winston";
const { SqlTransport } = require("winston-sql-transport");

const transportConfig = {
client: "mysql2",
connection: {
host: "localhost",
user: "root",
password: "Mahdi54321",
database: "todos",
// port: "3307",
},
tableName: "logs",
};

const alignColorsAndTime = winston.format.combine(
winston.format.colorize({
all: true,
}),
winston.format.label({
label: "[LOGGER]",
}),
winston.format.timestamp({
format: "YYYY-MM-DD HH:mm:ss",
}),
winston.format.printf(
(info) => `${info.label} ${info.timestamp} ${info.level} : ${info.message}`
)
);

export const logger = winston.createLogger({
level: "debug",
transports: [
new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
alignColorsAndTime
),
}),
new winston.transports.File({
filename: "logs/example.log",
format: winston.format.combine(
winston.format.timestamp({
format: "YYYY-MM-DD HH:mm:ss",
}),
winston.format.json()
),
}),
new SqlTransport(transportConfig),
],
});

它只保存第一个日志,下一个只保存在文件中,不保存在数据库中。

我猜 new SqlTransport(transportConfig), 不会每次都运行,所以它可以将每个日志保存到数据库。

如何将每一条日志都保存到mysql数据库中?

最佳答案

您使用的包已弃用,您可以使用 winston-mysql 包:https://www.npmjs.com/package/winston-mysql

根据文档的实现示例:

const options_default = {
host: 'localhost',
user: 'logger',
password: 'logger*test',
database: 'WinstonTest',
table: 'sys_logs_default'
};

//custom log table fields
const options_custom = {
host: 'localhost',
user: 'logger',
password: 'logger*test',
database: 'WinstonTest',
table: 'sys_logs_custom',
fields: {level: 'mylevel', meta: 'metadata', message: 'source', timestamp: 'addDate'}
};

//meta json log table fields
const options_json = {
host: 'localhost',
user: 'logger',
password: 'logger*test',
database: 'WinstonTest',
table: 'sys_logs_json'
};

const logger = winston.createLogger({
level: 'debug',
format: winston.format.json(),
defaultMeta: { service: 'user-service' },
transports: [
new winston.transports.Console({
format: winston.format.simple(),
}),
// or use: options_custom / options_json
new winstonMysql(options_default),
],
});

const rnd = Math.floor(Math.random() * 1000);
const msg = `test message ${rnd}`;

logger.debug(msg, {message: msg, type: 'demo'});
logger.error(msg, {message: msg, type: 'demo'});
logger.info(msg, {message: msg, type: 'demo'});
logger.warn(msg, {message: msg, type: 'demo'});

关于javascript - 如何将 winston 日志文件保存到 mysql 数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73215060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com