day.js used to handle parses, validates, manipulates, and displays dates and times for modern browsers with a largely Moment.js-compatible API on the server side.
Step 1: Installing Required Dependencies
The first step is to install the necessary dependencies for our logging monitor. In your project directory, run the following command:
Create a new file called logger.ts in your src/server/logger folder. This file will contain a utility function to set up logging using Morgan and Chalk. Add the following code to logger.ts:
This utility function creates a Morgan logger instance and uses Chalk to colorize the output. It also includes the current timestamp using DayJS.
Step 3: Setting up Logging Middleware
Create a new file called loggingMiddleware.ts in your src/server/logger folder. This file will contain middleware to add our logger utility to Express. Add the following code to loggingMiddleware.ts:
This middleware simply calls our logger utility function to log requests to the console.
Step 4: Adding Logging Middleware to Express
In your Next.js app, create a new file called server.ts in your project's root directory. This file will contain the code to set up Express and add our logging middleware. Add the following code to server.ts:
This code sets up an Express app and adds our logging middleware to log all requests.
Step 5: Updating Your package.json file
Update your package.json file to use server.ts as the entry point for your application. In the "scripts" section, replace the "start" command with the following:
This command tells Next.js to use server.ts as the custom server for our app.
Step 6: Testing the Logging Monitor
Build your app for production using the following command:
Then, start your app in production mode using the following command:
Visit your app in the browser and navigate to a few pages. You should see log messages in your console that look something like this:
These log messages include the timestamp, HTTP method, URL, response status, and response time for each request.