Const koa = require(const koa = require('koa');
const fs = require('fs');
const route = require('koa-route');
const app = new Koa();
const {format} = require('date-fns'); const date = new Date(); // Get the current timefunction getFileName() {
    const date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    return year + "-" + month + "-"+ day; } // Process the main information of the main logfunctionGetMessage (CTX) {// Get browser information const agent = ctx.request.header['user-agent'];
    const host = ctx.request.header.host;
    const method = ctx.request.method;
    const url = ctx.request.url;
    return host + ' ' + method + ' ' + url + ' '+ agent; } // Plan to distinguish types INFO(default) WARN ERROR by code or statusfunctionHandleLogger (CTX, code) {// loggerType is used to distinguish types of writes from fileslet loggerType = ' ';
    if (code === 200) {
        loggerType = 'INFO';
    } else if (code > 200 || code < 10001) {
        loggerType = 'WARN';
    } else {
        loggerType = 'ERROR'; } // LOGGER_PATH = path.resolve(process.cwd(),'loggers'); Const LOGGER_PATH = const LOGGER_PATH ='./loggers'; // Create a directory if the directory does not existif(! fs.existsSync(LOGGER_PATH)) { fs.mkdirSync(LOGGER_PATH); }letmessage = getMessage(ctx); // The file name, for example, info_2020-03-17. loglet fileName = `${LOGGER_PATH}/${loggerType}_${getFileName()}.log`; [INFO] localhost:9898 GET/Mozilla/5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML like Gecko) Chrome/80.0.3987.132 Safari/537.36+let loggerContent = `[${format(new Date(), 'yyy-MM-dd HH:mm:ss')}]     [${loggerType}]     ${message}+ \n`;
    fs.readFile(fileName, (err, data) => {
        if(err) {fs.writeFile(fileName, loggerContent, error => {if (error) return console.log("Failed to write file due to"+ error.message); // Simultaneously outputlog
                console.log(loggerContent);
            });
        } elseFs. writeFile(fileName, data + loggerContent, error => {// fs.writeFile(fileName, data + loggerContent, error => {fs.writeFile(fileName, data + loggerContent, error => {if (error) return console.log("Failed to write file due to"+ error.message); // Simultaneously outputlogconsole.log(loggerContent); }); }}); } const main = ctx => { handleLogger(ctx, 200); ctx.response.body ='Hello World';
};
const about = ctx => {
    ctx.response.body = 'Hello World';
    handleLogger(ctx, 10001);
};

app.use(route.get('/', main));
app.use(route.get('/about', about));

app.listen(9898);


Copy the code

Making address: https://github.com/peterbooy/my-logger