Log4js is a great logging module in Node.js. It’s very simple and easy to use. This article will share how to write a logging service quickly. Because of node’s middleware pattern, we will write the logging service as a middleware.

The following will write an access logging middleware using KOA as an example

Install log4js

npm install log4js
Copy the code

Description of log4JS configuration

log4js.configure({
  appenders: {
    visitor: {
      type: "dateFile".filename: `./logs/visitor-`.pattern: ".yyyy-MM-dd.log".alwaysIncludePattern: true.daysToKeep: 30.layout: {
        type: "messagePassThrough"}}},categories: { default: { appenders: ["visitor"].level: "info"}}});Copy the code

Appenders. Visitor We do some personalization, why do we do that?

  • type: "dateFile": Log files can be scrolled in a specific date mode, such as today output asvisitor-2019-03-08.logTomorrow lose asvisitor-2019-03-09.log;
  • filename: './logs/visitor.log': Sets the path and file name of the log output file
  • alwaysIncludePattern: true: Use the same Settings as above to generate log names per day
  • daysToKeep: 30: Logs are saved for only 30 dayslayout.typeWe set tomessagePassThrough, not applicable to the log template provided by Log4JS, completely use our own code, the advantage of this is that when our log is associated with Ali Cloud log must be written in JSON, in order to facilitate query and controllability, we need to use our own definition of JSON.

The complete code

const log4js = require("log4js");
log4js.configure({
  appenders: {
    visitor: {
      type: "dateFile".filename: `./logs/visitor.log`.alwaysIncludePattern: true.daysToKeep: 30.layout: {
        type: "messagePassThrough"}}},categories: { default: { appenders: ["visitor"].level: "info"}}});const logger = log4js.getLogger("visitor");

module.exports = function() {
  return async function(ctx, next) {
    const start = new Date(a);await next();
    // Filter by file end
    const index = ctx.url.lastIndexOf(".");
    const ext = ctx.url.substr(index + 1);
    const extArr = ["js"."png"."otf"."txt"."html"."xml"."json"."ico"]; 
    if (extArr.indexOf(ext) === - 1 ) {
      const end = new Date(a);CTX. IP + "I" this is for bad guys. If the IP ends with an "I" and is not your company's IP, there is a high probability that it is bad guys. If you're not using nginx, just fetch ctx.ip.
      const Uip =
        ctx.get("HTTP_X_REAL_IP") ||
        ctx.get("X-Read-IP") ||
        ctx.get("HTTP_X_FORWARDED_FOR") ||
        ctx.get("X-Forwarded-For") ||
        ctx.get("Remote_Addr") ||
        ctx.ip + "i";
      let data = {
        startTime: start.toJSON(),
        endTime: end.toJSON(),
        uri: ctx.url,
        ip: Uip || "".status: ctx.status,
        referrer: ctx.headers.referer || "".msec: end - start,
        ua: ctx.header["user-agent"]}; logger.info(JSON.stringify(data)); }}; };Copy the code