Table of Contents
Prerequisites
Step 1: Project Setup
Step 2: Installing Pino
Step 3: Creating the Logger Service
Step 4: Configuring Logs
Custom Log Levels
Pretty Printing
Step 5: Storing Logs in a File
Conclusion
Home Web Front-end CSS Tutorial How to Implement Logging in a Node.js Application With Pino-logger

How to Implement Logging in a Node.js Application With Pino-logger

Mar 19, 2025 am 09:52 AM

How to Implement Logging in a Node.js Application With Pino-logger

Effective logging is crucial for application development. It provides insights into application behavior and simplifies debugging. This tutorial demonstrates how to implement logging in a Node.js application using the Pino logger, a popular choice known for its performance and flexibility.

Pino allows comprehensive logging, including detailed information about application flow and the ability to save logs to separate files. Its extensive GitHub community further underscores its reliability.

This guide covers:

  • Configuring logging levels.
  • Customizing log output for improved readability in the terminal, including options for JSON response inclusion.
  • Saving logs to a dedicated file.

By the end, you'll be able to implement robust logging in your Node.js applications using best practices and Pino.

Prerequisites

Before proceeding, ensure you have:

  • Experience with Express.js for server-side development.
  • Familiarity with building REST APIs without authentication.
  • Proficiency with command-line tools or integrated terminals in code editors.

Using a tool like Postman for API endpoint testing is recommended.

Step 1: Project Setup

This step involves creating a basic Node.js CRUD application using Express.js and Mongoose. This approach ensures logging functionality is implemented within a realistic application context.

For the CRUD application setup, refer to a tutorial on performing CRUD operations with Mongoose and MongoDB Atlas. Once complete, you'll have a Node.js application with create, read, update, and delete routes.

Install nodemon for automatic server restarts upon code changes:

npm install -g --force nodemon
Copy after login

The -g flag installs globally, and --force handles potential conflicts.

Step 2: Installing Pino

Install the necessary dependencies: Pino, express-pino-logger, and pino-pretty:

npm install pino express-pino-logger pino-pretty
Copy after login

Step 3: Creating the Logger Service

Create a Pino logger service with various log levels (warning, error, info, etc.). This service will be integrated into your application using Node.js middleware.

Create a services directory:

mkdir services
Copy after login

Create loggerService.js inside services with the following code:

const pino = require('pino');
module.exports = pino({ prettyPrint: true });
Copy after login

This creates a basic logger with pretty-printed output. Later steps will cover further configuration.

Next, in your server.js file, import the logger service and express-pino-logger:

const expressPinoLogger = require('express-pino-logger');
const logger = require('./services/loggerService');
Copy after login

Configure express-pino-logger with your logger service:

// ...
const loggerMiddleware = expressPinoLogger({
  logger: logger,
  autoLogging: true,
});

app.use(loggerMiddleware);
// ...
Copy after login

autoLogging: true includes the JSON response in logs.

In your route handler (e.g., foodRoutes.js), import and use the logger:

const logger = require('../services/loggerService');

// ...
app.get("/food", async (request, response) => {
  logger.info('GET route accessed');
  // ...
});
// ...
Copy after login

Restart your server (nodemon server.js) and test the API endpoint. The log output will appear in your terminal.

Step 4: Configuring Logs

This step focuses on customizing the logger service and enhancing log readability.

Custom Log Levels

Define custom log levels in loggerService.js:

// ...
const levels = {
  http: 10,
  debug: 20,
  info: 30,
  warn: 40,
  error: 50,
  fatal: 60,
};
// ...
Copy after login

Update the pino configuration in loggerService.js:

module.exports = pino({
  prettyPrint: true,
  customLevels: levels,
  useOnlyCustomLevels: true,
  level: 'http',
});
Copy after login

Test with custom levels (e.g., logger.http(...)). Set autoLogging: false in server.js if the JSON response is unnecessary.

Pretty Printing

Enhance log formatting in loggerService.js:

module.exports = pino({
  customLevels: levels,
  useOnlyCustomLevels: true,
  level: 'http',
  prettyPrint: {
    colorize: true,
    levelFirst: true,
    translateTime: 'yyyy-dd-mm, h:MM:ss TT',
  },
});
Copy after login

Test again to see the improved log output.

Step 5: Storing Logs in a File

To write logs to a file, modify the pino configuration in loggerService.js:

module.exports = pino({
  customLevels: levels,
  useOnlyCustomLevels: true,
  level: 'http',
  prettyPrint: {
    colorize: true,
    levelFirst: true,
    translateTime: 'yyyy-dd-mm, h:MM:ss TT',
  },
}, pino.destination(`${__dirname}/logger.log`));
Copy after login

Test your API; logs will now be written to logger.log in the services directory.

Conclusion

This tutorial provided a comprehensive guide to implementing Pino logging in Node.js applications. Remember best practices: contextual information, clear purpose, and readable formatting are key to effective logging. Explore the official Pino documentation for advanced configuration options.

The above is the detailed content of How to Implement Logging in a Node.js Application With Pino-logger. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
A Comparison of Static Form Providers A Comparison of Static Form Providers Apr 16, 2025 am 11:20 AM

Let’s attempt to coin a term here: "Static Form Provider." You bring your HTML

A Proof of Concept for Making Sass Faster A Proof of Concept for Making Sass Faster Apr 16, 2025 am 10:38 AM

At the start of a new project, Sass compilation happens in the blink of an eye. This feels great, especially when it’s paired with Browsersync, which reloads

Weekly Platform News: HTML Loading Attribute, the Main ARIA Specifications, and Moving from iFrame to Shadow DOM Weekly Platform News: HTML Loading Attribute, the Main ARIA Specifications, and Moving from iFrame to Shadow DOM Apr 17, 2025 am 10:55 AM

In this week's roundup of platform news, Chrome introduces a new attribute for loading, accessibility specifications for web developers, and the BBC moves

Some Hands-On with the HTML Dialog Element Some Hands-On with the HTML Dialog Element Apr 16, 2025 am 11:33 AM

This is me looking at the HTML element for the first time. I've been aware of it for a while, but haven't taken it for a spin yet. It has some pretty cool and

Paperform Paperform Apr 16, 2025 am 11:24 AM

Buy or build is a classic debate in technology. Building things yourself might feel less expensive because there is no line item on your credit card bill, but

Weekly Platform News: Text Spacing Bookmarklet, Top-Level Await, New AMP Loading Indicator Weekly Platform News: Text Spacing Bookmarklet, Top-Level Await, New AMP Loading Indicator Apr 17, 2025 am 11:26 AM

In this week's roundup, a handy bookmarklet for inspecting typography, using await to tinker with how JavaScript modules import one another, plus Facebook's

Where should 'Subscribe to Podcast' link to? Where should 'Subscribe to Podcast' link to? Apr 16, 2025 pm 12:04 PM

For a while, iTunes was the big dog in podcasting, so if you linked "Subscribe to Podcast" to like:

Quick Gulp Cache Busting Quick Gulp Cache Busting Apr 18, 2025 am 11:23 AM

You should for sure be setting far-out cache headers on your assets like CSS and JavaScript (and images and fonts and whatever else). That tells the browser

See all articles