Tips for utilizing PINO to write logs to both file and console

I have successfully implemented logging to a log file using Pino. However, I am wondering if there is a way to also log to the console in order to manage the frequency of 'console.log()' calls.

  1. Node Version : 21.6.1
  2. Typescript Version : 5.3.3
  3. Pino Version : 8.18.0
  4. Pino Pretty Version : 10.3.1
import pino from 'pino';
import { getEnvConfig } from "config/env";

const envConfig = getEnvConfig();
const logdir: string = envConfig.log_dir;
const logfile: string = `${logdir}/appName-${new Date(Date.now()).toISOString().split('T')[0]}.log`;

export const logger = pino({
    level: envConfig.log_level ?? "info",
    formatters: {
        bindings: (bindings) => {
            return { pid: bindings.pid, host: bindings.hostname, node_version: process.version };
        },
        level: (label: string) => {
            return { level: label.toUpperCase() };
        },
    },
    timestamp: pino.stdTimeFunctions.isoTime,
    transport: ({ target: 'pino/file', options: { destination: logdir, mkdir: true } }),
});

Answer №1

As per the documentation, it is recommended to utilize pipelines to specify multiple transports for maintaining existing level formatters. Using pino-pretty, which utilizes STDIN and STDOUT, will result in output on the console.

import pino, { LoggerOptions } from 'pino';
import { getEnvConfig } from "config/env";

const envConfig = getEnvConfig();
const logdir: string = envConfig.log_dir;
const logfile: string = `${logdir}/appName-${new Date(Date.now()).toISOString().split('T')[0]}.log`;

const pinoOptions: LoggerOptions = {
    level: envConfig.log_level ?? "info",
    formatters: {
        bindings: (bindings) => {
            return { pid: bindings.pid, host: bindings.hostname, node_version: process.version };
        },
        level: (label: string) => {
            return { level: label.toUpperCase() };
        },
    },
    timestamp: pino.stdTimeFunctions.isoTime,
    transport: ({
        pipeline: [{
            target: 'pino-pretty', // installation required
        },
        {
            target: 'pino/file', options: { destination: logdir, mkdir: true },
        },
        ],
    }
    ),
}
export const logger = pino(pinoOptions);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Angular to Transform an Array of Dates

I have an array of dates which returns: [Mon Aug 03 2020 00:00:00 GMT+0100 (British Summer Time), Wed Aug 05 2020 00:00:00 GMT+0100 (British Summer Time)] I am looking to convert these into the following format: ["2020-02-13T02:39:51.054", &quo ...

Retrieving latitude and longitude from place id in an Angular Google Maps component

Currently utilizing the google-maps component to extract latitude and longitude from Google Maps prediction data. Additionally, I have integrated a search bar using google-maps component. I have successfully implemented a search bar with ngx-google-places ...

Issue with ngRX infinite loop caused by the updateOne function in the adapter

Hey there, I'm struggling to figure out why my code is stuck in an infinite loop. I've searched online extensively but haven't found a solution that fits my specific issue. This is the code snippet causing the problem: /** * CODE ...

Best practice for reusing test logic in Cypress when dealing with dynamic DOM re-rendering

I'm encountering an issue while testing my app with Cypress. Let's say I have a table with items, and I want to verify that it's possible to delete all the items from the table. The table is rendered using React and re-renders after each del ...

Upon initial loading, the default sidenav in Angular is not selected

I need to ensure that the sidenav loads the basic page during the initial load. This is controlled by the routing.ts file shown below: import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; i ...

Learning to implement forwardRef in MenuItem from Material-UI

Encountering an error when pressing Select due to returning MenuItem in Array.map. Code const MenuItems: React.FC<{ items: number[] }> = (props) => { const { items } = props; return ( <> {items.map((i) => { return ( ...

Cannot locate AngularJS + Typescript controller

I'm encountering an error while attempting to integrate TypeScript with AngularJS. The issue I'm facing is: Error: [$controller:ctrlreg] The controller named 'MyController' has not been registered Does anyone have any insights on what ...

PhpStorm 2019.2 introduces Material UI components that have optional props instead of being mandatory

My PhpStorm 2019.2 keeps showing me a notification that the Button component from Material UI needs to have an added href prop because it is required. However, when I refer to the Material UI API, I see something different. Take a look at this screenshot: ...

Troubleshooting: Vue.js component events not being detected in TypeScript

I'm encountering an issue with receiving events from a barcode reader, which I heavily referenced from a GitHub repository. The problem lies in the fact that the events emitted by the BarcodeScanner component are not being captured by the enclosing c ...

Deactivate the rows within an Office UI Fabric React DetailsList

I've been attempting to selectively disable mouse click events on specific rows within an OUIF DetailsList, but I'm facing some challenges. I initially tried overriding the onRenderRow function and setting CheckboxVisibility to none, but the row ...

Combining a pair of canvases

Currently, I am utilizing a JavaScript library to create a QR Code. This library generates the QR code by displaying it on a canvas. Nevertheless, my goal is to integrate a background behind this QR Code. I attempted to achieve this by first drawing the b ...

When using Angular, NestJS, and TypeORM, an issue may arise where null values are

My coworker and I are currently collaborating on a client project. We are utilizing NestJS for the backend, Angular for the frontend, and MySQL for the database. We have encountered an issue that we are struggling to resolve: Within the Entity of the Ne ...

Angular CLI - exploring the depths of parent-child component communication

My issue revolves around accessing the 'edit' method of a child component using @ViewChild, but for some reason it's not functioning as expected. Where could I possibly be going wrong? Here are the console logs: https://i.sstatic.net/wvpVN ...

Validating Credit Card Numbers with Spaces

Currently, I am in the process of creating a credit card form that requires validation using checkValidity to match the specific card pattern that is dynamically added to the input field. For example, if a user enters a Mastercard number such as 545454545 ...

Unable to compile TypeScript files using gulp while targeting ES5

After starting my first Angular2 app, I encountered an issue where I couldn't use gulp to compile for es5. Below is the dependencies file: "dependencies": { "@angular/common": "2.0.0", "@angular/compiler": "2.0.0", "@angular/compiler-cli ...

Obtain a tuple of identical length from a function

I'm attempting to create a function that returns a tuple with the same length as the parameter tuple passed to it. Although I tried using generics, I am encountering an error when applying the spread operator on the result. My goal is best illustrate ...

Transfer your focus to the following control by pressing the Enter key

I came across a project built on Angular 1.x that allows users to move focus to the next control by pressing the Enter key. 'use strict'; app.directive('setTabEnter', function () { var includeTags = ['INPUT', 'SELEC ...

Developing a personalized validation function using Typescript for the expressValidator class - parameter is assumed to have a type of 'any'

I'm seeking to develop a unique validation function for express-validator in typescript by extending the 'body' object. After reviewing the helpful resource page, I came across this code snippet: import { ExpressValidator } from 'expre ...

When a new array object is added to a nested array in a React Redux reducer, the array in the store is correctly updated but the React component

I am brand new to React and redux. Currently, I have a task where I need to implement workflows with tasks inside them. While I successfully managed to add a new workflow object to the state array, I encountered a problem when trying to add a new task - it ...

Insert a new item into a current array using Typescript and Angular

-This is my curated list- export const FORMULARLIST: formular[] = [ { id: 1, name: 'Jane Doe', mobileNumber: 987654, secondMobileNumber: 456789, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e1bcc0d9ec ...