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
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
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
Create loggerService.js
inside services
with the following code:
const pino = require('pino'); module.exports = pino({ prettyPrint: true });
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');
Configure express-pino-logger
with your logger service:
// ... const loggerMiddleware = expressPinoLogger({ logger: logger, autoLogging: true, }); app.use(loggerMiddleware); // ...
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'); // ... }); // ...
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, }; // ...
Update the pino
configuration in loggerService.js
:
module.exports = pino({ prettyPrint: true, customLevels: levels, useOnlyCustomLevels: true, level: 'http', });
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', }, });
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`));
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!

Custom cursors with CSS are great, but we can take things to the next level with JavaScript. Using JavaScript, we can transition between cursor states, place dynamic text within the cursor, apply complex animations, and apply filters.

Interactive CSS animations with elements ricocheting off each other seem more plausible in 2025. While it’s unnecessary to implement Pong in CSS, the increasing flexibility and power of CSS reinforce Lee's suspicion that one day it will be a

Tips and tricks on utilizing the CSS backdrop-filter property to style user interfaces. You’ll learn how to layer backdrop filters among multiple elements, and integrate them with other CSS graphical effects to create elaborate designs.

Well, it turns out that SVG's built-in animation features were never deprecated as planned. Sure, CSS and JavaScript are more than capable of carrying the load, but it's good to know that SMIL is not dead in the water as previously

Yay, let's jump for text-wrap: pretty landing in Safari Technology Preview! But beware that it's different from how it works in Chromium browsers.

This CSS-Tricks update highlights significant progress in the Almanac, recent podcast appearances, a new CSS counters guide, and the addition of several new authors contributing valuable content.

Most of the time, people showcase Tailwind's @apply feature with one of Tailwind's single-property utilities (which changes a single CSS declaration). When showcased this way, @apply doesn't sound promising at all. So obvio

Deploying like an idiot comes down to a mismatch between the tools you use to deploy and the reward in complexity reduced versus complexity added.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download
The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version
Chinese version, very easy to use

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
