Logging Node.js logs on Papertrail using Pino

Introduction

This article will help you set up your logs with papertrail with your existing Node.js application

Pre-requisites

Basic knowledge of Node.js, Yarn/NPM, importing and exporting nodejs packages within files.

I will talk in the first person so bear with me 😀

Lets Start Stepwise

  • I created a new directory on my desktop and named logging
  • Then fired up a terminal in this folder.
  • Created a basic project using yarn, feel free to use npm
yarn init
  • Added 3 packages
yarn add node-cron pino pino-papertrail
  • Created a logger.js file which will export our Pino transport logger.
// logger.js
module.exports =  require('pino')();
  • Create an entry file for our project execution index.js
var cron = require('node-cron');
// import our logger
const logger = require('./logger');

// add a cron that will run every 15 seconds
cron.schedule('*/15 * * * * *', () => {
  logger.info('logging every 15 seconds');
});
  • Created a new log destination using the big button below.
  • Used next screen with default settings, hit Create
    image

  • Next screen will show up to your log destination variables
    image

Starting Our Application

In our project terminal, use this command to throw all our logs to papertrail. Update your variables (obviously) for host, port and app name accordingly.

node index | pino-papertrail --host <logs.papertrailapp.com> --port <PORT> --appname <NAME_OF_APP>

Output : Project Console

Here’s my terminal console

<14>1 2021-07-16T22:30:45.438+05:30 rohit testApp 14993 - - {"level":30,"time":1626474645438,"pid":14993,"hostname":"rohit","msg":"logging every 15 seconds"}
<14>1 2021-07-16T22:31:00.458+05:30 rohit testApp 14993 - - {"level":30,"time":1626474660458,"pid":14993,"hostname":"rohit","msg":"logging every 15 seconds"}
<14>1 2021-07-16T22:31:15.475+05:30 rohit testApp 14993 - - {"level":30,"time":1626474675475,"pid":14993,"hostname":"rohit","msg":"logging every 15 seconds"}
<14>1 2021-07-16T22:31:30.491+05:30 rohit testApp 14993 - - {"level":30,"time":1626474690491,"pid":14993,"hostname":"rohit","msg":"logging every 15 seconds"}
<14>1 2021-07-16T22:31:45.510+05:30 rohit testApp 14993 - - {"level":30,"time":1626474705510,"pid":14993,"hostname":"rohit","msg":"logging every 15 seconds"}

Output : Papertrail Event logs

Thats it.

Follow for more upcoming articles. 🙃

12