search
HomeWeb Front-endJS TutorialIntroduction to the method of encapsulating and developing Koa log middleware


This article brings you an introduction to the Koa log middleware packaging and development methods. It has certain reference value. Friends in need can For reference, I hope it will be helpful to you.

For a server application, log recording is essential. We need to use it to record what the project program does every day, when errors occurred, what errors occurred, etc., for future convenience. Review and grasp the running status of the server in real time and restore problem scenarios.

The function of log

Record the running status of the server program; help developers quickly capture errors, locate and solve faults.

Log middleware development tool log4js

There is no built-in log module in node, so you need to use a third-party module. Use the module: log4js installation: npm i log4js -Slogsjs official documentation

Log classification:

Access log: records the client's access to the project, mainly http requests. Used to help improve and enhance the performance and user experience of the website; Application log: The log printed by the project mark and recording location, including abnormal situations, to facilitate querying the running status of the project and locating bugs (including debug, info, warn and error, etc. level).

Log level

If the log level is configured, it can only record log information with a higher level than the set log level. Log level diagram

Introduction to the method of encapsulating and developing Koa log middleware

If level: 'error' is configured, only error, fatar, and mark level log information can be output.

Log middleware development

Set the information segment that needs to be recorded in the log ( log_info.js)

export default (ctx, message, commonInfo) => {
    const {
      method,  // 请求方法
      url,          // 请求链接
      host,      // 发送请求的客户端的host
      headers      // 请求中的headers
    } = ctx.request;
    const client = {
      method,
      url,
      host,
      message,
      referer: headers['referer'],  // 请求的源地址
      userAgent: headers['user-agent']  // 客户端信息 设备及浏览器信息
    }
    return JSON.stringify(Object.assign(commonInfo, client));
}
  1. Set a universal acquisition configured log4js object (logger.js)
const getLog = ({env, appLogLevel, dir}, name) => {
    
    //log4js基本说明配置项,可自定义设置键名,用于categories.appenders自定义选取
    let appenders = {
        // 自定义配置项1
        cheese: {
            type: 'dateFile', //输出日志类型
            filename: `${dir}/task`,  //输出日志路径
            pattern: '-yyyy-MM-dd.log', //日志文件后缀名(task-2019-03-08.log)
            alwaysIncludePattern: true
        }
    }
    // 如果为开发环境配置在控制台上打印信息
    if (env === "dev" || env === "local" || env === "development") {
        // 自定义配置项2
        appenders.out = {
          type: "stdout"
        }
    }
    // log4js配置
    let config = {
        appenders,
        //作为getLogger方法获取log对象的键名,default为默认使用
        categories: {
          default: {
            appenders: Object.keys(appenders), // 取appenders中的说有配置项
            level: appLogLevel
          }
        }
    }
    log4js.configure(config) //使用配置项
    return log4js.getLogger(name)// 这个cheese参数值先会在categories中找,找不到就会默认使用default对应的appenders,信息会输出到yyyyMMdd-out.log
}
  1. log log middleware development (logger.js)
export default (options) => {
    const contextLogger = {}; //后期赋值给ctx.log
    const { env, appLogLevel, dir, serverIp, projectName } = Object.assign({}, baseInfo, options || {});
    // 取出通用配置(项目名,服务器请求IP)
    const commonInfo = { projectName, serverIp };

    const logger = getLog({env, appLogLevel, dir},'cheese');

    return async (ctx, next) => {
        const start = Date.now(); //日志记录开始时间
        // 将日志类型赋值ctx.log,后期中间件特殊位置需要记录日志,可直接使用ctx.log.error(err)记录不同类型日志
        methods.forEach((method, i) => {
            contextLogger[method] = (message) => {
                logger[method](logInfo(ctx, message, commonInfo))
            }
        })
        ctx.log = contextLogger;
        // 执行中间件
        await next()
        // 结束时间
        const responseTime = Date.now() - start;
        // 将执行时间记录logger.info
        logger.info(logInfo(ctx,
            {
                responseTime: `响应时间为${responseTime/1000}s`
            }, commonInfo)
        )
    }
}
  1. Middleware usage (app.js)
import Log from '../log/logger';
...
app.use(Log({
        env: app.env,  // koa 提供的环境变量
        projectName: 'back-API',
        appLogLevel: 'debug',
        dir: 'logs',
        serverIp: ip.address()
    }))
  1. Other special locations require logging usage
ctx.log.error(err.stack); //记录错误日志
ctx.log.info(err.stack); // 记录信息日志
ctx.log.warn(err.stack); // 记录警告日志
...
  1. Running screenshot

Introduction to the method of encapsulating and developing Koa log middleware

##log4js uses basic configuration and process analysis

    Set configuration items,
  1. // 配置项形式
    {
        appenders:{
            [自定义key]:{}
        },
        categories:{
        }
    }
    // 配置
    config: {
        appenders:{
            // 每一个属性可以看作为一个配置模块
            out: {
                type: 'dateFile', //输出日志类型
                filename: `log/task`,  //输出日志路径
                pattern: '-yyyy-MM-dd.log', //日志文件后缀名(task-2019-03-08.log)
                ...//具体配置看官网
            },
            error: {
                type: 'dateFile',
                filename: 'log/error',
                pattern: '-yyyy-MM-dd.log'',
                "alwaysIncludePattern": true
            },
            stdout: { type: 'stdout' }, //在控制台上打印信息
        },
        // 通过categories来取出给log4js按需配置,返回配置后的log4js对象,每个属性配置相当于一个不同的log4js配置对象入口;default为默认入口(getLogger()找不到入口时默认使用default)
        categories:{
            // 配置默认入口,使用appenders中的'stdout','out'配置模块,记录trace以上等级日志
            default: { appenders: ['stdout','out'], level: 'trace' },
            // 配置error门入口,使用appenders中的'stdout','err'配置模块,记录error以上等级日志
            error : {appenders: ['err'], level: 'error'}
        }
    }
Use let logger_out = log4js.getLogger('app');

log4js.getLogger('app') to find a specific log4js object process: first search in categories based on the app parameter value, and find that there is no app , and then the appenders corresponding to default will be used for configuration by default, that is, the information will be output to the log/task-yyyy-mm-dd.log file, and will be output to the console

Use let logger_out = log4js. getLogger('error');

Search in the categories based on the error parameter value and find that there is no error configuration. Then the appenders corresponding to the error will be used for configuration, that is, the information will be output to log/error-yyyy- In the mm-dd.log file, because the stdout module is not used in the error configuration item appenders, the information will not be output to the console.

Consider later

whether the log needs to be stored in a database. Carry out log persistence; considering that it is impossible to save log records forever, there may be no need to store logs from a month or a week ago. It is necessary to develop settings to automatically delete expired log files at regular intervals (obtain database log records)

The above is the detailed content of Introduction to the method of encapsulating and developing Koa log middleware. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software