Enhancing your logs with pino-pretty: Including file names in each log line

Looking to include file name in the pino-pretty output line,
currently using:

const pino = require('pino');
const logger = pino({
    prettyPrint: {
        colorize: true,
        translateTime: 'yyyy-mm-dd HH:MM:ss',
        ignore: 'pid,hostname'
    }
})

Resulting output:

[2020-05-14 16:25:45] INFO : Network is private

Desired output:

[2020-05-14 16:25:45] INFO myFile.js: Network is private

Trying to achieve this by using the customPrettifiers option but haven't been successful so far,
for example attempted solution:

const pino = require('pino');
const path = require('path');
const logger = pino({
    prettyPrint: {
        colorize: true,
        translateTime: 'yyyy-mm-dd HH:MM:ss',
        ignore: 'pid,hostname',
        customPrettifiers: {
            filename: path.basename(__filename)
        }
    }
})

Answer №1

If you're looking for a solution that comes close to what you need, consider the following code snippet:

const path = require('path');
const pino = require('pino');
const logger = pino({
  prettyPrint: {
    // Includes the filename property in the message
    messageFormat: '{filename}: {msg}',

    // Excludes 'filename' from displaying beneath each log
    ignore: 'pid,hostname,filename', 
  },
}).child({ filename: path.basename(__filename) });

Keep in mind that it's not possible to style the filename differently from the message, but this workaround should suffice.


For better organization, it might be preferable to create a separate logger.js file where the default pino options are set like so:

// logger.js
const logger = require('pino')({
  prettyPrint: {
    messageFormat: '{filename}: {msg}',
    ignore: 'pid,hostname,filename', 
  },
});
module.exports = logger;
// file_with_logging.js
const parentLogger = require('./logger.js');
const logger = parentLogger.child({ filename: path.basename(__filename) });

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

Using arrays in the request body with Node.js Express framework

Trying to include an array in the request body for a POST call to MongoDB, aiming to insert a new document upon success. See my current code snippet below: app.post(`/api/add`, async (req, res) => { collection.create({ 'id': req.body.id, ...

What is the function of Node.js within a Polymer configuration?

What are the reasons for requiring Node.js installation when working with Polymer? Is it solely for npm purposes? Are there additional functions of Node.js in a standard Polymer project, or is npm primarily used to install Bower and Bower is used to inst ...

Creating Authentic PEM Keys with NodeJS for Message Signing and Verifying

Background This information is sourced from the NodeJS documentation on TLS/SSL for Node v10.9.0 (2018-AUG) Visit this link for more details. openssl genrsa -out ryans-key.pem 2048 The above command will result in: -----BEGIN RSA PRIVATE KEY----- base ...

Is it possible to invoke a helper function by passing a string as its name in JavaScript?

I'm encountering a certain issue. Here is what I am attempting: Is it possible to accomplish this: var action = 'toUpperCase()'; 'abcd'.action; //output ===> ABCD The user can input either uppercase or lowercase function ...

How can I pass command line variables into an npm script?

I am facing an issue where I am attempting to pass a command line option (which is not stored in version control) to my main script index.js. This script performs specific actions based on a designated S3 bucket. Here is the relevant section from my packa ...

Combine the running of the app and the mocking of tests into a single Grunt command within the Gr

I currently have a fully functional Node.js Express REST API application. Great. In addition, I have successfully created a Mocha/Chai/Supertest mock to test the API application mentioned above. Excellent. However, the issue arises when I need to manuall ...

Create a Rest API and implement server-side rendering concurrently using SailsJs

I am exploring the potential of utilizing the SailsJs framework for nodeJs in order to create an application. Initially, my plan was to construct a REST API in Sails and utilize AngularJs for managing the Front-End. This API would also be beneficial for o ...

The function fs.readFileSync does not exist in the context of Meteor and React

Hey there, I'm encountering an issue in Chrome debugger where it says 'fs.readFileSync is not a function' when I try to use readFileSync(); This is how I set it up... const fs = require('fs'); I then proceeded to execute the fun ...

Retrieve the most recent update of the GitLab repository when specifying it as a dependency in the package.json file

I have a private GitLab repository where I store a NodeJs module with files like package.json and index.js. In another project, I want to include this repository as a dependency using the following syntax: "package-name": "git+ssh://git@gitlab01:path/to/r ...

Caution: npm installation warns about potential issues

After encountering some WARN messages, I attempted to update npm by running npm audit fix However, this resulted in even more WARN messages. When I tried to install all dependencies using npm i I was bombarded with a plethora of WARN messages (see below) ...

problem with asynchronous functions in sails.js

I decided to put sails.js asynchronous performance to the test by writing a code snippet that would wait for 10 seconds. My expectation was that the code should be executed asynchronously due to the callback function. Upon visiting the URL where the code w ...

Should functions in node.js be refactored into their own route or kept within the existing route design?

Hello, I am just starting to learn about node.js. In terms of designing routes that should be accessible... Let's consider an event route with the usual GET, POST, PUT, DELETE methods. If in my front-end application, I need to frequently update an eve ...

Unexpected database query result in Node.js

In my newuser.js file for a node.js environment with a mongodb database managed through mongoose, I have the following code: //newuser.js //This code is responsible for creating new user documents in the database and requires a GET parameter along with a ...

Error: The function expressValidator is not recognized in the current environment. This issue is occurring in a project utilizing

I am currently working on building a validation form with Express and node. As a beginner in this field, I encountered an error in my console that says: ReferenceError: expressValidator is not defined index.js code var express = require('express& ...

Mongoose failing to retrieve complete data set

In the setup of my Model, I have defined it as follows: var Post = mongoose.Schema({ "_uid": String, "post_title": String, "post_content": String, "post_date": Date, "user": String, "slug": String, "attached_medi ...

Increased capacities with content and acceptance encoding headers

Consider the following scenario: I send a POST request from the client server to a REST API with a payload size of 20-30MB, where the content is gzip compressed at the network level due to the request header configuration. Do I also need to enable gzip c ...

The exclude option in Nest JS middleware does not prevent the middleware from running on excluded routes

I'm having an issue with excluding certain routes from the middleware. The .exclude option doesn't seem to be working as expected, as the middleware is still being applied to the excluded routes. Here is the code for the Middleware: https://i.st ...

Is the auto-import feature in the new VSCODE 1.18 compatible with nodelibs installed via npm?

Testing out the latest auto-import feature using a JS file in a basic project. After npm installing mongoose and saving an empty JS file for editing, I anticipate that typing const Schema = mongoose. will trigger an intellisense menu with mongoose nodelib ...

Error in Winston: Unable to determine the length of undefined property

I encountered an issue with my Winston Transport in the express backend of my MERN app. The error message reads: error: uncaughtException: Cannot read property 'length' of undefined TypeError: Cannot read property 'length' of undefi ...

the function does not output any value

I am currently facing an issue with my function called IsValidUrl(). This function is supposed to return values based on a certain condition (either false or true). However, there seems to be another function within it that is preventing the values from be ...