JS的console日志保存

2023-12-26 17:03:18

JS的console日志保存

// 日志文件保存路径
const logpath = '/data/robotsLogs/'
if (!fs.existsSync(logpath)) {
    fs.mkdirSync(logpath, { recursive: true }); // recursive: true, 逐层创建文件目录,默认是false
}
// 获取当前时间
const now = new Date();
// 格式化成年-月-日形式
const folderName = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;
const logwritepath = logpath + folderName + '-info-log.txt'
const logwriteerrpath = logpath + folderName + '-err-log.txt'
// 创建写入流对象
let writeStream = fs.createWriteStream(logwritepath, { flags: 'a', encoding: 'utf-8' }); // a表示追加内容而不是覆盖原有内容
// 重定向标准输出(console.log)到写入流
process.stdout.write = (data) => {
    const now = new Date();
    const nowFileName = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;
    if (folderName != nowFileName) {
        // 获取当前时间
        // 格式化成年-月-日形式
        const logwritepath = logpath + nowFileName + '-info-log.txt'
        writeStream = fs.createWriteStream(logwritepath, { flags: 'a', encoding: 'utf-8' });
    }
    writeStream.write(data);
};
let writeStreamErr = fs.createWriteStream(logwriteerrpath, { flags: 'a', encoding: 'utf-8' }); // a表示追加内容而不是覆盖原有内容
// 重定向标准输出(console.error)到写入流
process.stderr.write = (data) => {
    const now = new Date();
    const nowFileName = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;
    if (folderName != nowFileName) {
        // 获取当前时间
        // 格式化成年-月-日形式
        const logwriteerrpath = logpath + nowFileName + '-err-log.txt'
        writeStreamErr = fs.createWriteStream(logwriteerrpath, { flags: 'a', encoding: 'utf-8' });
    }
    writeStreamErr.write(data);
};

文章来源:https://blog.csdn.net/qq_39389646/article/details/135223183
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。