1

I'm new to Strapi and Koa. I'm trying to generate strapi- console log output using custom log format.

For custom configuration of logging middleware in strapi, I came across following documentation: logger middleware which uses winstonjs for logging.

Custom Log format which I'm trying to generate should log in below format:

[timestamp-YYYY-MM-DD HH:MM:SS] - [loglevel] - [Client IP or REQUEST-IP] - [HTTP-METHOD REQUEST-URL - REQUEST_BODY(incase of POST) RESPONSE TIME(ms)- HTTP-STATUSCODE] [User-Agent]

As of now, I'm able to log following set of information- timestamp,loglevel,http-method,request-url,http-statuscode and http-response time

The place where I'm stuck and scratching my head is in logging remaining set of parameters. i.e. CLIENT_IP/REQUEST-IP, HTTP-Request Body and User-Agent

Please suggest.

2 Answers 2

0

To customize what you zant your logs look like you'd better customize the strapi logger middleware in the node_modules folder since it seems like this is is not pointed out in the docs.

Edit the strapi logger middleware

Here below youcan find the complete steps for doing that as for strapi v4:

  1. Edit the [strapi_project_folder]\node_modules\@strapi\strapi\lib\middlewares\logger.js file and especially the strapi.log.http() method.
  2. This const ip_address = ctx.request.ip; is the client's ip unless she/he is not under a proxy.
  3. So your log.http function calling should look like this : strapi.log.http(${ctx.method} ${ctx.url} (${delta} ms) ${ctx.status} ${agent} ${platform} ${ip_address});. You can notice that in my case I have added other information apart from the client's ip address.
  4. Save your changes.

After a successful testing; to make these change still when someone or yourself will clone your project, here is when the patch-package tool comes in.

Using patch-package to persist the changes

Following these steps will help you persist your change into the node_modules folder even after you remove it and reinstall your npm packages.

  1. Run npm install patch-package to the install the package
  2. Add this line in your package.json file under scripts; "postinstall": "patch-package"
  3. Run npx patch-package @strapi/strapi to snapshot your changer into the strapi files
Sign up to request clarification or add additional context in comments.

Comments

0

You must create custom middlleware which will be used instead of standart one.

Here is how to do it:

Create file /src/middlewares/request-logger.ts

export default (config, { strapi }) => {
  return async (context, next) => {
    const start = Date.now();

    await next();

    const delta = Math.ceil(Date.now() - start);
    const ip =
      context.request.ip ||
      context.request.headers["x-forwarded-for"] ||
      context.request.headers["x-real-ip"] ||
      context.ip ||
      "unknown";

    strapi.log.http(`${ip} | ${context.status} ${delta.toString().padStart(3)}ms ${context.method} ${context.url}`);

    if (context.status < 400) {
      return;
    }

    strapi.log.error("============================================");

    if (context.status >= 500) {
      strapi.log.error("INTERNAL SERVER ERROR DETAILS");
    }

    if (context.status >= 400 && context.status < 500) {
      strapi.log.error("CLIENT ERROR DETAILS");
    }

    strapi.log.error("============================================");
    strapi.log.error(`Status code: ${context.status}`);
    strapi.log.error(`Message: ${context.response.message}`);
    strapi.log.error(`IP Address: ${ip}`);
    strapi.log.error(`Method: ${context.method}`);
    strapi.log.error(`URL: ${context.url}`);
    strapi.log.error(`User-Agent: ${context.request.headers["user-agent"] || "N/A"}`);
    strapi.log.error(`Context: ${JSON.stringify(context.request, null, 2)}`);

    if (context.request.body && Object.keys(context.request.body).length > 0) {
      strapi.log.error(`Request Body: ${JSON.stringify(context.request.body, null, 2)}`);
    }

    if (context.request.query && Object.keys(context.request.query).length > 0) {
      strapi.log.error(`Request Query: ${JSON.stringify(context.request.query, null, 2)}`);
    }

    strapi.log.error("============================================");
  };
};


and register it in /config/middlewares.ts

export default [
  // "strapi::logger", // We will disable standart one
  "global::request-logger", // And register our custom middleware

  // Here existing middlewares ...  
];

I have used Nginx as reverse proxy, so I have to scan headers for real request IP address

Also, if you are using Nginx, you have to configure Nginx to proxy headers.

Configure koa-proxy in /config/server.ts:

export default ({ env }) => ({
  host: env("HOST", "0.0.0.0"),
  port: env.int("PORT", 1337),
  url: env("URL", "http://localhost:1337"),
  app: {
    keys: env.array("APP_KEYS"),
  },
  proxy: {
    koa: true,
  },
});

Here is nginx configuration /etc/nginx/sites-available/example.com:

upstream strapi {
    server 127.0.0.1:1337;
}

server {
    listen 80;
    server_name example.com;

    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate     /etc/ssl/abc/example.com.pem;
    ssl_certificate_key /etc/ssl/abc/privatekey.key;

    location / {
        proxy_pass http://strapi;
        proxy_http_version 1.1;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header Host $host;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_pass_request_headers on;
        include proxy_params;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.