Nuxt SSR: Logging with response time into access.log and error.log
Asked Answered
P

2

5

I use Nuxt with SSR and would like to have something similar to apaches access.log and error.log

Especially I'm interested in the response time for each call.

I couldn't find anything in the nuxt documentation. Do I have to implement this feature on my own?

Petronius answered 16/2, 2022 at 8:59 Comment(0)
T
4

You can add a custom server middleware that uses morgan:

At its simplest, the middleware would look like:


    // server-middleware/logging.js
    import morgan from 'morgan';
    export default morgan('combined');

In your Nuxt config:


    // nuxt.config.js
    export default {
      serverMiddleware: [
        '~/server-middleware/logging'
      ]
    };

This configuration will result in "combined" format logging to stdout. Consult the morgan package's documentation to see how to tailor the output to include response time, and to log to files instead of stdout.

Thanos answered 23/2, 2022 at 11:56 Comment(0)
A
2

To use morgan as logging middleware for Nuxt 3, run npm install morgan, then create the file /server/middleware/morgan.ts with the following contents:

import morgan from "morgan";

export default defineEventHandler((event) => {
  var logger = morgan("tiny");
  logger(event.node.req, event.node.res, function () {});
});

You should then get output on the server console similar to the following (for the tiny format specified above, and assuming you have /server/api/search.get.ts defined and working):

GET /api/search?term=123 200 - - 169.540 ms

You can then change the morgan format to get more extensive logging if required.

Alcoholicity answered 17/10, 2023 at 10:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.