Multithreaded Logging with Pino

Rate this content
Bookmark
The video discusses logging in Node.js applications, focusing on the Pino logger. Pino is known for its high performance and minimal overhead, making it a great choice for efficient logging. The speaker explains how Pino processes log data synchronously to avoid memory leaks and CPU slowdowns. The use of Worker Threads in Pino helps in processing logs without blocking the main thread, improving overall performance. Pino.Transport is introduced as a new function that supports log processing in a worker thread, allowing for multiple log destinations and pretty printing. The talk also covers the use of a Ring Buffer for efficient communication between the main thread and worker threads. Finally, there is a demo showing Pino's capabilities, including sending logs to Elasticsearch and visualizing them with Kibana.

From Author:

Almost every developer thinks that adding one more log line would not decrease the performance of their server... until logging becomes the biggest bottleneck for their systems! We created one of the fastest JSON loggers for Node.js: pino. One of our key decisions was to remove all "transport" to another process (or infrastructure): it reduced both CPU and memory consumption, removing any bottleneck from logging. However, this created friction and lowered the developer experience of using Pino and in-process transports is the most asked feature our user.

In the upcoming version 7, we will solve this problem and increase throughput at the same time: we are introducing pino.transport() to start a worker thread that you can use to transfer your logs safely to other destinations, without sacrificing neither performance nor the developer experience.

This talk has been presented at JSNation Live 2021, check out the latest edition of this JavaScript Conference.

FAQ

Matteo Collina is a member of the technical steering committee, co-creator of Fastify and Pino, and a software architect who helps companies implement Node.js in production. He works for Nearform, a professional services company based in Ireland.

Pino is a fast logger for Node.js with a minimal feature set, focusing on performance and efficiency. It is designed to reduce the overhead of logging in applications and is part of a larger Node.js ecosystem.

Using Pino in Node.js involves creating a logger through a factory function and then using methods like info, warn, error, and debug to log messages. Pino also supports child logger functionality for more granular logging control.

Pino offers high performance with minimal IO overhead, supports structured logging in JSON format, and provides features like child loggers. Its design helps in reducing memory pressure and CPU usage during logging activities.

Pino improves performance by processing log data synchronously within the same macro tick, avoiding additional memory allocation and reducing the event loop blockage, thereby enhancing throughput and reducing latency.

Matteo Collina
Matteo Collina
19 min
11 Jun, 2021

Comments

Sign in or register to post your comment.

Video Transcription

Available in Español: Registro Multihilo con Pino

1. Introduction to Pino Logging

Short description:

Today I'm going to talk about logging. I work for Nearform, a professional services company based in Ireland. I'm a member of the technical steering committee and co-creator of Fastify and Pino. Pino is one of the fastest loggers for Node.js with a minimal feature set. It has been downloaded 6 million times per month and we are working on version seven. Using Pino is simple with a factory function and it helps reduce the hover rate of logging inside your application.

Hi, everyone, I am Matteo Collina. Today I'm going to talk about one of my favorite topics, logging. Just a little bit of intro of me before we start. I'm Matteo Collina, at Matteo Collina on Twitter. I work for a company called Nearform. We are a professional services company based in Ireland. I'm also a member of the technical steering committee and I'm the co-creator of Fastify and these libraries we're talking today, Pino. I'm also a software architect, so I typically help companies run Node.js in production. I also write every week on a new my newsletter at nodeland.dev, please subscribe.

Anyway, as part of my, oh, this is actually important. Maybe I have a lot of downloads on NPM. I ended up maintaining a lot of things in the ecosystem because as my activity as a consultant, I tend to balance between client work and the need of the client with the maintaining Node.js as ecosystem, and that is a good synergy. So I end up implementing new libraries and new modules to solve problems that my clients have, and I bring those new things to my clients. As part of this initiative I built up various things like Fastify and Pino. Pino, what's Pino? Pino is one of the fastest logger for Node.js. It does a minimal feature set, so we'll talk a little bit about the minimal, and it is a great community. Pino's now been downloaded 6 million times per month, and we have four collaborators. Maybe three, but whatever, four collaborators. And it's version six, and we are working on version seven. This talk, it's about version seven. Hey, this is actually nice. So new things coming through.

How do you use Pino? Using Pino is very simple. You can just create your logger. Use just a factory function, so you just create your logger, and then you start doing info, warn, error, debug, those things that you like. We also have this child logger functionality that enables you to create a new child with a certain set of properties already pre-populated, and it's a newline delimited JSON logger, so it produces newline delimited JSON, so it's a JSON followed by a newline, and another JSON followed by a newline. Pretty interesting. It's fast, and you can use pnode to drastically reduce the hover rate of logging inside your application. You cannot really bring it to zero because it's still doing IO in the end, but it helps reducing it quite a lot. Know that logging should be fast.

2. The Speed and Performance of Pina Logging

Short description:

You should not have very expensive logging because if you have very expensive logging, then you will be inclined to log less and not more, and you need more observability most of the time. Pina's been around for a bit, so, hey, happy days. And most of what we say is still modern. The first bit that I want to cover about Pina is how come it is so fast. This diagram explains the event loop and how to achieve a very performant IEO in Node.js and authorized performance Node.js applications. When that lands in the JavaScript land, it means that, well, before doing that, the event loop called some C++. So in the side, the C++ code inside Node.js, then we kick off the JavaScript function, which is a function that gets executed, which in turn, might resolve a promise or schedule a next tick. And therefore, we have to process also the microtick queues. From the moment we move from the... We start calling inside C++ to the moment that we return, we let C++ return, the event loop is blocked. So there's no more event, no nothing. There's nothing happening IO-wise in the system. One of the... What happens if you have a slow IO operation? So let's imagine in the context of login that you're writing to a destination and you need to do some mangling and processing of your logs before moving them out. Now because of, you know, and you're writing all those logs and you have a slow, then therefore you have a slow IO operation and the amount of tasks, concurrent tasks increase. But if the concurrent task, asynchronous concurrent tasks increase, then it also increase the memory consumption of your application.

You should not have very expensive logging because if you have very expensive logging, then you will be inclined to log less and not more, and you need more observability most of the time.

There is this nice talk called the Cost of Logging that my partner in crime, David Marklamas, and myself have done at node-conf.eu 2016. It's a long time ago, you know? But Pina's been around for a bit, so, hey, happy days. And you can check it out because it was a really good... It's a really good talk. And most of what we say is still modern. There was a bunch of things that are different and we're going to change in v7 that we're going to talk about soon.

So, well, the first bit that I want to cover about Pina in how come it is so fast. How can it be fast? Well, I just want to give you a little bit of overall. And thank you, James. These slides are amazing. This diagram is probably one of the best ones we have ever done. This diagram explains the event loop and explains when we're doing IEO and how can we achieve and how to achieve a very performant IEO in Node.js and authorized performance Node.js applications.

So first and foremost, you have data that is coming on the event loop. So you have data, you have events coming in. So some IEO has finished or maybe an HTTP request has arrived. When that lands in the JavaScript land, it means that, well, before doing that, the event loop called some C++. So in the side, the C++ code inside Node.js, then we kick off the JavaScript function, which is a function that gets executed, which in turn, might resolve a promise or schedule a next tick. And therefore, we have to process also the microtick queues. After all of that is said and done, we go back into the event loop. From the moment we move from the... We start calling inside C++ to the moment that we return, we let C++ return, the event loop is blocked. So there's no more event, no nothing. There's nothing happening IO-wise in the system. This is not great. Well, or it is great in the sense that it's, you know, if I want to make it fast, if you make my code fast, the time I spend executing JavaScript needs to be as small as possible. So... One of the... What happens in, you know, if you have a slow IO operation? So let's imagine in the context of login that you're writing to a destination and you need to do some mangling and processing of your logs before moving them out. Now because of, you know, and you're writing all those logs and you have a slow, then therefore you have a slow IO operation and you, the amount of tasks, concurrent tasks increase, right? But if the concurrent task, asynchronous concurrent tasks increase, then it also increase the memory consumption of your application.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

It's a Jungle Out There: What's Really Going on Inside Your Node_Modules Folder
Node Congress 2022Node Congress 2022
26 min
It's a Jungle Out There: What's Really Going on Inside Your Node_Modules Folder
Top Content
The talk discusses the importance of supply chain security in the open source ecosystem, highlighting the risks of relying on open source code without proper code review. It explores the trend of supply chain attacks and the need for a new approach to detect and block malicious dependencies. The talk also introduces Socket, a tool that assesses the security of packages and provides automation and analysis to protect against malware and supply chain attacks. It emphasizes the need to prioritize security in software development and offers insights into potential solutions such as realms and Deno's command line flags.
Towards a Standard Library for JavaScript Runtimes
Node Congress 2022Node Congress 2022
34 min
Towards a Standard Library for JavaScript Runtimes
Top Content
There is a need for a standard library of APIs for JavaScript runtimes, as there are currently multiple ways to perform fundamental tasks like base64 encoding. JavaScript runtimes have historically lacked a standard library, causing friction and difficulty for developers. The idea of a small core has both benefits and drawbacks, with some runtimes abusing it to limit innovation. There is a misalignment between Node and web browsers in terms of functionality and API standards. The proposal is to involve browser developers in conversations about API standardization and to create a common standard library for JavaScript runtimes.
ESM Loaders: Enhancing Module Loading in Node.js
JSNation 2023JSNation 2023
22 min
ESM Loaders: Enhancing Module Loading in Node.js
ESM Loaders enhance module loading in Node.js by resolving URLs and reading files from the disk. Module loaders can override modules and change how they are found. Enhancing the loading phase involves loading directly from HTTP and loading TypeScript code without building it. The loader in the module URL handles URL resolution and uses fetch to fetch the source code. Loaders can be chained together to load from different sources, transform source code, and resolve URLs differently. The future of module loading enhancements is promising and simple to use.
Out of the Box Node.js Diagnostics
Node Congress 2022Node Congress 2022
34 min
Out of the Box Node.js Diagnostics
This talk covers various techniques for getting diagnostics information out of Node.js, including debugging with environment variables, handling warnings and deprecations, tracing uncaught exceptions and process exit, using the v8 inspector and dev tools, and generating diagnostic reports. The speaker also mentions areas for improvement in Node.js diagnostics and provides resources for learning and contributing. Additionally, the responsibilities of the Technical Steering Committee in the TS community are discussed.
Node.js Compatibility in Deno
Node Congress 2022Node Congress 2022
34 min
Node.js Compatibility in Deno
Deno aims to provide Node.js compatibility to make migration smoother and easier. While Deno can run apps and libraries offered for Node.js, not all are supported yet. There are trade-offs to consider, such as incompatible APIs and a less ideal developer experience. Deno is working on improving compatibility and the transition process. Efforts include porting Node.js modules, exploring a superset approach, and transparent package installation from npm.
Building a modular monolith with Fastify
Node Congress 2023Node Congress 2023
30 min
Building a modular monolith with Fastify
Top Content
Fastify is a powerful tool for building web applications and APIs in Node.js, with millions of downloads per month. It promotes encapsulation and structuring through plugins and decorators, allowing for code and data segmentation. The talk emphasizes the importance of modularizing applications by domains and features, and showcases a demo of a typical Fastify application. The speaker also discusses the benefits of using Platformattic for refactoring and launching Fastify applications in the cloud. The Q&A section covers topics such as dependency injection and debugging, while also highlighting the importance of separating business logic from API contracts.

Workshops on related topic

Node.js Masterclass
Node Congress 2023Node Congress 2023
109 min
Node.js Masterclass
Top Content
Workshop
Matteo Collina
Matteo Collina
Have you ever struggled with designing and structuring your Node.js applications? Building applications that are well organised, testable and extendable is not always easy. It can often turn out to be a lot more complicated than you expect it to be. In this live event Matteo will show you how he builds Node.js applications from scratch. You’ll learn how he approaches application design, and the philosophies that he applies to create modular, maintainable and effective applications.

Level: intermediate
Build and Deploy a Backend With Fastify & Platformatic
JSNation 2023JSNation 2023
104 min
Build and Deploy a Backend With Fastify & Platformatic
WorkshopFree
Matteo Collina
Matteo Collina
Platformatic allows you to rapidly develop GraphQL and REST APIs with minimal effort. The best part is that it also allows you to unleash the full potential of Node.js and Fastify whenever you need to. You can fully customise a Platformatic application by writing your own additional features and plugins. In the workshop, we’ll cover both our Open Source modules and our Cloud offering:- Platformatic OSS (open-source software) — Tools and libraries for rapidly building robust applications with Node.js (https://oss.platformatic.dev/).- Platformatic Cloud (currently in beta) — Our hosting platform that includes features such as preview apps, built-in metrics and integration with your Git flow (https://platformatic.dev/). 
In this workshop you'll learn how to develop APIs with Fastify and deploy them to the Platformatic Cloud.
Building a Hyper Fast Web Server with Deno
JSNation Live 2021JSNation Live 2021
156 min
Building a Hyper Fast Web Server with Deno
WorkshopFree
Matt Landers
Will Johnston
2 authors
Deno 1.9 introduced a new web server API that takes advantage of Hyper, a fast and correct HTTP implementation for Rust. Using this API instead of the std/http implementation increases performance and provides support for HTTP2. In this workshop, learn how to create a web server utilizing Hyper under the hood and boost the performance for your web apps.
0 to Auth in an Hour Using NodeJS SDK
Node Congress 2023Node Congress 2023
63 min
0 to Auth in an Hour Using NodeJS SDK
WorkshopFree
Asaf Shen
Asaf Shen
Passwordless authentication may seem complex, but it is simple to add it to any app using the right tool.
We will enhance a full-stack JS application (Node.JS backend + React frontend) to authenticate users with OAuth (social login) and One Time Passwords (email), including:- User authentication - Managing user interactions, returning session / refresh JWTs- Session management and validation - Storing the session for subsequent client requests, validating / refreshing sessions
At the end of the workshop, we will also touch on another approach to code authentication using frontend Descope Flows (drag-and-drop workflows), while keeping only session validation in the backend. With this, we will also show how easy it is to enable biometrics and other passwordless authentication methods.
Table of contents- A quick intro to core authentication concepts- Coding- Why passwordless matters
Prerequisites- IDE for your choice- Node 18 or higher
GraphQL - From Zero to Hero in 3 hours
React Summit 2022React Summit 2022
164 min
GraphQL - From Zero to Hero in 3 hours
Workshop
Pawel Sawicki
Pawel Sawicki
How to build a fullstack GraphQL application (Postgres + NestJs + React) in the shortest time possible.
All beginnings are hard. Even harder than choosing the technology is often developing a suitable architecture. Especially when it comes to GraphQL.
In this workshop, you will get a variety of best practices that you would normally have to work through over a number of projects - all in just three hours.
If you've always wanted to participate in a hackathon to get something up and running in the shortest amount of time - then take an active part in this workshop, and participate in the thought processes of the trainer.
Mastering Node.js Test Runner
TestJS Summit 2023TestJS Summit 2023
78 min
Mastering Node.js Test Runner
Workshop
Marco Ippolito
Marco Ippolito
Node.js test runner is modern, fast, and doesn't require additional libraries, but understanding and using it well can be tricky. You will learn how to use Node.js test runner to its full potential. We'll show you how it compares to other tools, how to set it up, and how to run your tests effectively. During the workshop, we'll do exercises to help you get comfortable with filtering, using native assertions, running tests in parallel, using CLI, and more. We'll also talk about working with TypeScript, making custom reports, and code coverage.