Skip to content

Commit

Permalink
feat: log output to file (#338)
Browse files Browse the repository at this point in the history
* feat: log output to file

* fix type

* fix: logs path use current work dir

* feat: add cleanLog function to sanitize log strings

* fix replace

* remove rplace datetime in nestjs log
  • Loading branch information
nini22P authored Nov 23, 2024
1 parent 767e64b commit 1a4fde7
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
55 changes: 55 additions & 0 deletions packages/terre2/src/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import * as fs from 'fs';
import * as path from 'path';

const logsDir = path.join(process.cwd(), 'logs');
const logFile = path.join(logsDir, 'log.txt');
const logFileMaxSize = 1024 * 1024;

// 确保日志目录存在
if (!fs.existsSync(logsDir)) {
try {
fs.mkdirSync(logsDir);
} catch (error) {
console.error('Error creating logs directory:', error);
}
}

const checkLogFileSize = (filePath: string, maxSize: number) => {
fs.stat(filePath, (err, stats) => {
if (!err && stats.size > maxSize) {
const oldLogFile = filePath.replace('log.txt', 'log.old.txt');
fs.rename(filePath, oldLogFile, (renameErr) => {
if (renameErr) {
console.error('Error renaming log file:', renameErr);
}
});
}
});
};

// 替换特殊字符
const cleanLog = (log: string) => log.replace(/(\x1B\[[0-9;]*m)/g, '');

// 在启动时检查日志文件大小
checkLogFileSize(logFile, logFileMaxSize);

const logStream = fs.createWriteStream(logFile, { flags: 'a' });

const originalStdoutWrite = process.stdout.write;
const originalStderrWrite = process.stderr.write;

process.stdout.write = function (...args: any[]) {
try {
logStream.write(`${new Date().toISOString()} [LOG]: ${cleanLog(args[0])}`);
} catch (_) {}
return originalStdoutWrite.apply(process.stdout, args);
};

process.stderr.write = function (...args: any[]) {
try {
logStream.write(
`${new Date().toISOString()} [ERROR]: ${cleanLog(args[0])}`,
);
} catch (_) {}
return originalStderrWrite.apply(process.stderr, args);
};
1 change: 1 addition & 0 deletions packages/terre2/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { urlencoded, json } from 'express';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { env } from 'process';
import { WsAdapter } from '@nestjs/platform-ws';
import './logger';

let WEBGAL_PORT = 3000; // default port
export const version_number = `4.5.10`;
Expand Down

0 comments on commit 1a4fde7

Please sign in to comment.