已通过Instrumentation Hook配置Next.js+App Insights,如何在页面中调用日志?
在Next.js页面中使用App Insights记录日志的方案
一、服务端组件/API路由中使用(Node.js环境)
你已在instrumentation.ts中完成服务端App Insights初始化,服务端代码(Server Components、API路由、Server Actions等)可直接导入applicationinsights调用默认客户端:
- 在服务端TSX文件(如
app/page.tsx,默认是Server Component)中:
import appInsights from 'applicationinsights'; export default async function Home() { // 记录追踪日志 appInsights.defaultClient.trackTrace({ message: '服务端页面加载日志', severity: appInsights.Contracts.SeverityLevel.Information }); // 记录自定义事件 appInsights.defaultClient.trackEvent({ name: 'HomePageVisited', properties: { source: 'Server Component' } }); return <h1>Home Page</h1>; }
二、客户端组件中使用(浏览器环境)
浏览器环境无法直接使用Node.js的applicationinsights包,需使用专门的浏览器SDK @microsoft/applicationinsights-web,步骤如下:
- 安装客户端SDK:
npm install @microsoft/applicationinsights-web
- 创建客户端初始化工具文件
app/utils/appInsightsClient.ts:
import { ApplicationInsights } from '@microsoft/applicationinsights-web'; let appInsightsInstance: ApplicationInsights | null = null; export const initAppInsightsClient = () => { if (typeof window !== 'undefined' && !appInsightsInstance) { appInsightsInstance = new ApplicationInsights({ config: { connectionString: process.env.NEXT_PUBLIC_APPINSIGHTS_CONNECTION_STRING, enableAutoRouteTracking: true, // 自动追踪路由变化 enableAutoPageUnloadEvents: true } }); appInsightsInstance.loadAppInsights(); } return appInsightsInstance; }; export const getAppInsightsClient = () => { if (!appInsightsInstance) { throw new Error('App Insights客户端未初始化,请先调用initAppInsightsClient'); } return appInsightsInstance; };
- 在客户端组件中使用(需添加
'use client'指令):
'use client'; import { useEffect } from 'react'; import { initAppInsightsClient, getAppInsightsClient } from '@/app/utils/appInsightsClient'; export default function ClientComponent() { useEffect(() => { const appInsights = initAppInsightsClient(); // 记录页面加载事件 appInsights?.trackEvent({ name: 'ClientComponentLoaded' }); // 记录追踪日志 appInsights?.trackTrace({ message: '客户端组件初始化完成', severityLevel: 1 // 0=Verbose,1=Information,2=Warning,3=Error,4=Critical }); }, []); const handleClick = () => { // 记录按钮点击事件 getAppInsightsClient().trackEvent({ name: 'TestButtonClicked', properties: { buttonLabel: '测试日志' } }); }; return <button onClick={handleClick}>测试日志</button>; }
三、统一封装工具函数(可选)
为避免重复代码,可创建通用日志工具文件app/utils/logger.ts,同时支持服务端和客户端:
import appInsights from 'applicationinsights'; import { getAppInsightsClient } from './appInsightsClient'; export const logTrace = (message: string, severity?: any) => { if (process.env.NEXT_RUNTIME === 'nodejs') { appInsights.defaultClient.trackTrace({ message, severity: severity || appInsights.Contracts.SeverityLevel.Information }); } else { try { getAppInsightsClient().trackTrace({ message, severityLevel: severity || 1 }); } catch (err) { console.warn('App Insights客户端未初始化,日志降级到控制台:', message); } } }; export const logEvent = (eventName: string, properties?: Record<string, any>) => { if (process.env.NEXT_RUNTIME === 'nodejs') { appInsights.defaultClient.trackEvent({ name: eventName, properties }); } else { try { getAppInsightsClient().trackEvent({ name: eventName, properties }); } catch (err) { console.warn('App Insights客户端未初始化,事件降级到控制台:', eventName, properties); } } };
在任意组件中调用:
// 服务端组件 import { logTrace } from '@/app/utils/logger'; export default async function ServerPage() { logTrace('服务端页面访问日志'); return <h1>Server Page</h1>; }
// 客户端组件 'use client'; import { useEffect } from 'react'; import { initAppInsightsClient, logEvent } from '@/app/utils/logger'; export default function ClientPage() { useEffect(() => { initAppInsightsClient(); logEvent('ClientPageVisited'); }, []); return <h1>Client Page</h1>; }
注意事项
- 环境变量:服务端连接字符串可使用普通环境变量(如
APPINSIGHTS_CONNECTION_STRING),客户端必须使用NEXT_PUBLIC_前缀的环境变量(如NEXT_PUBLIC_APPINSIGHTS_CONNECTION_STRING),确保能在浏览器中访问。 - 避免重复初始化:通过单例模式封装客户端实例,防止多次调用
loadAppInsights。 - 降级处理:客户端初始化前调用日志方法时,添加控制台输出的降级逻辑,避免页面报错。
内容的提问来源于stack exchange,提问作者devram
相关产品推荐
相关产品推荐

