You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将NestJS应用的Pino日志发送至Azure Application Insights

将NestJS的Pino日志发送到Azure Application Insights

实现步骤

1. 安装依赖包

首先安装Pino到Application Insights的专用传输器:

npm install pino-applicationinsights

2. 配置环境变量

在你的.env文件中添加Azure Application Insights的连接字符串:

AZURE_APPINSIGHTS_CONNECTION_STRING="你的连接字符串"

3. 修改Pino配置

更新你的Pino配置文件,在生产环境下替换为Application Insights传输器:

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',
          },
        }
      : {
          target: 'pino-applicationinsights',
          options: {
            connectionString: process.env.AZURE_APPINSIGHTS_CONNECTION_STRING,
            // 可选:自定义日志级别与Application Insights severity的映射
            severityMapping: {
              trace: 'Verbose',
              debug: 'Debug',
              info: 'Information',
              warn: 'Warning',
              error: 'Error',
              fatal: 'Critical',
            },
          },
        },
  },
};

export default pinoConfig;

4. 验证现有配置

你的main.ts已经正确启用了NestJS-Pino的Logger和错误拦截器,无需额外修改:

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();

注意事项

  • 确保生产环境中AZURE_APPINSIGHTS_CONNECTION_STRING环境变量已正确配置
  • 传输器会自动将Pino日志转换为Application Insights兼容格式,包含请求ID、状态码等关键信息
  • 若需自定义日志字段映射,可在传输器的options中添加对应配置项

内容的提问来源于stack exchange,提问作者Emeka Obasi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 09:05:36