|
| 1 | +import fs from "fs"; |
| 2 | +import path from 'path'; |
| 3 | +import pino from "pino"; |
| 4 | +import Fastify from "fastify"; |
| 5 | +import {fileURLToPath} from 'url'; |
| 6 | +import {createStream} from 'rotating-file-stream'; |
| 7 | + |
| 8 | +const __filename = fileURLToPath(import.meta.url); |
| 9 | +const __dirname = path.dirname(__filename); |
| 10 | +const logDirectory = path.join(__dirname, '../logs'); |
| 11 | +if (!fs.existsSync(logDirectory)) { |
| 12 | + fs.mkdirSync(logDirectory); |
| 13 | +} |
| 14 | +// 自定义时间戳函数,格式为 YYYY-MM-DD HH:mm:ss |
| 15 | +const customTimestamp = () => { |
| 16 | + const now = new Date(); |
| 17 | + const yyyy = now.getFullYear(); |
| 18 | + const mm = String(now.getMonth() + 1).padStart(2, '0'); |
| 19 | + const dd = String(now.getDate()).padStart(2, '0'); |
| 20 | + const hours = String(now.getHours()).padStart(2, '0'); |
| 21 | + const minutes = String(now.getMinutes()).padStart(2, '0'); |
| 22 | + const seconds = String(now.getSeconds()).padStart(2, '0'); |
| 23 | + const formattedTime = `${yyyy}-${mm}-${dd} ${hours}:${minutes}:${seconds}`; |
| 24 | + return `,"time":"${formattedTime}"`; // 返回格式化后的时间戳 |
| 25 | +}; |
| 26 | + |
| 27 | +// const logStream = fs.createWriteStream(path.join(logDirectory, 'output.log'), { |
| 28 | +// flags: 'a', |
| 29 | +// encoding: 'utf8', |
| 30 | +// }); |
| 31 | +// 配置日志文件的轮转 |
| 32 | + |
| 33 | +const logStream = createStream(path.join(logDirectory, 'output.log'), { |
| 34 | + size: '500M', // 设置最大文件大小为 500MB |
| 35 | + compress: true, // 自动压缩旧的日志文件 |
| 36 | + encoding: 'utf8', // 设置日志文件的编码为 utf8 |
| 37 | + interval: '1d' // 每天轮转一次日志 |
| 38 | +}); |
| 39 | +export const fileLogger = pino( |
| 40 | + { |
| 41 | + // 使用标准的时间戳函数并格式化为 ISO 格式 |
| 42 | + // timestamp: pino.stdTimeFunctions.isoTime, |
| 43 | + timestamp: customTimestamp, |
| 44 | + }, |
| 45 | + logStream |
| 46 | +); |
| 47 | + |
| 48 | +// 创建两个 logger 实例 |
| 49 | +const consoleLogger = pino({ |
| 50 | + level: "debug", // 设置记录的最低日志级别 |
| 51 | + serializers: { |
| 52 | + req: pino.stdSerializers.req, // 标准请求序列化器 |
| 53 | + res: pino.stdSerializers.res, // 标准响应序列化器 |
| 54 | + }, |
| 55 | + // timestamp: pino.stdTimeFunctions.isoTime, |
| 56 | + timestamp: customTimestamp, |
| 57 | + // transport: { |
| 58 | + // target: 'pino-pretty', |
| 59 | + // options: { |
| 60 | + // translateTime: true, |
| 61 | + // singleLine: true, // 强制单行输出 |
| 62 | + // colorize: false, // 禁用颜色,保持纯 JSON |
| 63 | + // ignore: 'reqId,remoteAddress,remotePort', |
| 64 | + // }, |
| 65 | + // }, |
| 66 | +}, logStream); |
| 67 | +// const fastify = Fastify({logger: true}); |
| 68 | +// 初始化 Fastify 实例,使用 consoleLogger 输出控制台日志 |
| 69 | +export const fastify = Fastify({ |
| 70 | + logger: consoleLogger, |
| 71 | +}); |
0 commit comments