在NextJS中,你如果使用Vercel来部署,那么vercel自带了API接口和页面的一些监控和分析功能,不过都不是免费的,同时如果你不使用vercel来部署,用自己的云服务器部署,那么监控的一环就更加必不可少了;
这里推荐一下Axiom:
vercel托管
Vercel首先是支持直接connect axiom账户的,所以如果你本来就托管在vercel,那么可以方便的接入Axiom;
self host
但是如果你是self host:
1.安装Axiom:
bun add nex-axiom
2.配置next.config.ts:
import type { NextConfig } from 'next' import { withAxiom } from 'next-axiom' const nextConfig: NextConfig = { output: 'standalone', } export default withAxiom(nextConfig)
3.设置环境变量:
NEXT_PUBLIC_AXIOM_DATASET=synth NEXT_PUBLIC_AXIOM_TOKEN=xaat-95bbc794-27b8-4d0d-9dea-e13a1d8ce79c NEXT_PUBLIC_AXIOM_LOG_LEVEL=info
4.封装Logger组件:
为了以后可以方便的切换其他监控供应商,你应该自己封装一个Logger组件:
src/lib/logger/index.ts /* eslint-disable @typescript-eslint/no-explicit-any */ import { log } from 'next-axiom' export const logger = { info: (message: string, data?: Record<string, any>) => { log.info(message, data) }, error: (message: string, data?: Record<string, any>) => { log.error(message, data) }, }
5.使用logger:
服务端使用:
logger.info('Payment completed', { userID: '123', amount: '25USD' })
客户端使用:
客户端使用也需要封装的
'use client'; import { useLogger } from 'next-axiom'; export default function ClientComponent() { const log = useLogger(); log.debug('User logged in', { userId: 42 }); return <h1>Logged in</h1>; }