How do I Send my pino logs from my nestjs application to application insights in azure

257 Views Asked by At

This is my pino config

import { config } from 'dotenv';
import { Params } from 'nestjs-pino';

config();


const pinoConfig: Params = {
  pinoHttp:
    {
      level: process.env.NODE_ENV !== 'production' ? 'debug' : 'info',
      formatters: {
        level: (label, number) => {
          return { level: label };
        },
      },
      customReceivedMessage: function(req, res) {
        return `request ${req.id} received: ${req.method} ${req.url}`;
      },
      customSuccessMessage: function(req, res) {
        return `${req.method} ${req.url} completed`;
      },
      customErrorMessage: function(req, res, err) {
        return `request ${req.id} to ${req.method} ${req.url} errored with status code: ${res.statusCode} message: ${err.message}}`;
      },
      
      transport: process.env.NODE_ENV !== 'production'
        ?
        {
          target: 'pino-pretty',
          options: {
            singleLine: true,
            ignore: 'pid,hostname,req.headers,req.remotePort,req.remoteAddress,req,res',

          }
        }
        : undefined
      ,
      
    }
};

export default pinoConfig;

And in my main.ts file

import { NestFactory, Reflector } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule } from '@nestjs/swagger';
import { Logger, LoggerErrorInterceptor } from 'nestjs-pino';


async function bootstrap() {
  const PORT = process.env.PORT || 3001;
  const HOST = process.env.HOST || 'localhost';
  const PROTOCOL = process.env.PROTOCOL || 'http';
  const app = await NestFactory.create(AppModule, { cors: true });
  app.useLogger(app.get(Logger));
  app.useGlobalInterceptors(new LoggerErrorInterceptor());

...
  await app.listen(PORT);
  const serverUrl = `${PROTOCOL}://${HOST}:${PORT}`;

...
}

bootstrap();

The pino logs work correctly in local. However, I want to also send those logs to application insights in azure. How do i do this? I have already created an app insights resource and know my instrumentation and connection keys.

1

There are 1 best solutions below

2
On

By using the applicationinsights npm package - npm install applicationinsights.

  • Import the package and set up Application Insights in the main.ts file:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { TelemetryClient } from 'applicationinsights';
import { setupInstrumentation } from 'applicationinsights/NestJs';

async function bootstrap() {
  const PORT = process.env.PORT || 3001;
  const HOST = process.env.HOST || 'localhost';
  const PROTOCOL = process.env.PROTOCOL || 'http';

  // Initialize Application Insights
  const instrumentationKey = 'YOUR_INSTRUMENTATION_KEY'; // Replace with your key
  const telemetryClient = new TelemetryClient(instrumentationKey);
  setupInstrumentation(telemetryClient);

  const app = await NestFactory.create(AppModule, { cors: true });

  // Start Application Insights telemetry
  telemetryClient.trackNodeHttpDependency();

  await app.listen(PORT);
  const serverUrl = `${PROTOCOL}://${HOST}:${PORT}`;

  console.log(`Application is running on: ${serverUrl}`);
}

bootstrap();
  • Update the pinoConfig.ts file to include the Azure Application Insights transport.

pinoConfig.ts:

import { config } from 'dotenv';
import { Params } from 'nestjs-pino';
import { TelemetryClient } from 'applicationinsights';

config();

// Initialize the Application Insights client
const appInsights = new TelemetryClient(process.env.APP_INSIGHTS_INSTRUMENTATION_KEY);

const pinoConfig: Params = {
  pinoHttp: {
    level: process.env.NODE_ENV !== 'production' ? 'debug' : 'info',
    formatters: {
      level: (label, number) => {
        return { level: label };
      },
    },
    customReceivedMessage: function (req, res) {
      return `request ${req.id} received: ${req.method} ${req.url}`;
    },
    customSuccessMessage: function (req, res) {
      return `${req.method} ${req.url} completed`;
    },
    customErrorMessage: function (req, res, err) {
      return `request ${req.id} to ${req.method} ${req.url} errored with status code: ${res.statusCode} message: ${err.message}}`;
    },
    transport: [
      {
        target: 'pino-pretty',
        options: {
          singleLine: true,
          ignore: 'pid,hostname,req.headers,req.remotePort,req.remoteAddress,req,res',
        },
      },
      // Add Azure Application Insights transport
      {
        target: 'pino-azure-appinsights',
        options: {
          client: appInsights,
        },
      },
    ],
  },
};

export default pinoConfig;

You can find the instrumentation key in portal>application insights>overview.

enter image description here

Check the logs in the app insight>Investigate>Transaction search.

enter image description here enter image description here