-
-
Notifications
You must be signed in to change notification settings - Fork 58
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* 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
Showing
2 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters