课程名称: 新版 Node.js+Express+Koa2 开发Web Server博客
课程章节: 8-6 写日志
课程讲师: 双越
课程内容:
blog-1文件中创建
- logs 文件目录
- access.log 文件,存储访问日志
- error.log 文件,存储错误日志
- event.log 文件,存储自定义事件日志
- utils 工具目录
- log.js 文件,编写日志写入功能
urils/log.js
日志写入功能
const fs = require("fs");
const path = require("path");
// 写日志
function writeLog(writeStream, log) {
// 文件中写入东西
writeStream.write(log + "\n");
}
// 生成 write Stream
function createWriteStream(fileName) {
// 找到要写入的日志文件
const fullFilename = path.resolve(__dirname, "../", "../", "logs", fileName);
const writeStream = fs.createWriteStream(fullFilename, {
flags: "a", //a 追加的意思
});
return writeStream;
}
// 写访问日志
const accessWriteStream = createWriteStream("access.log");
function access(log) {
writeLog(accessWriteStream, log);
}
module.exports = {
access,
};
课程收获:
- 了解node中如何写入日志