app.use((req, res, next) => {
    let time = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
    const log = `
        ---------------------------------
        1)请求方式:${req.method},\n
        2)请求路径:${req.url},\n
        3)请求时间:${time},\n
        ---------------------------------
     `;
    // 写入文件
    fs.appendFile(path.join(__dirname,'req.log'),log,(err)=>{
        if(err) throw err;
        next();
    });
})

使用

// 1. 引入
const express = require('express')
const fs = require('fs')
const moment = require('moment')
const path = require('path')
// 2. 创建web服务器
const app = express();

// 4. 写日志
app.use((req, res, next) => {
    let time = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
    const log = `
        ---------------------------------
        1)请求方式:${req.method},\n
        2)请求路径:${req.url},\n
        3)请求时间:${time},\n
        ---------------------------------
     `;
    // 写入文件
    fs.appendFile(path.join(__dirname,'req.log'),log,(err)=>{
        if(err) throw err;
        next();
    });
})

app.get('/',(req, res) => {
    res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
    res.write("<h1>Hello</h1>");
    res.end();
})
// 3. 开启监听
app.listen(3000,'127.0.0.1',() => {
    console.log('服务器已启动!');
})