refactor(env): centralize app environment detection
This commit is contained in:
+28
-7
@@ -3,13 +3,34 @@
|
||||
*
|
||||
* 原始 Dart: lib/utils/app_env_util.dart
|
||||
*
|
||||
* 替代 `AppEnvUtil.isDevelopment`:基于 Next.js 注入的 `process.env.NODE_ENV`。
|
||||
* 基于 `.env*` 中的 `NEXT_PUBLIC_APP_ENV` 判断当前业务环境。
|
||||
*
|
||||
* 注意:该变量带 `NEXT_PUBLIC_` 前缀,可同时用于服务端和客户端代码。
|
||||
*/
|
||||
export const isDevelopment = (): boolean =>
|
||||
process.env.NODE_ENV !== "production";
|
||||
export type AppEnv = "development" | "test" | "production";
|
||||
|
||||
export const isProduction = (): boolean =>
|
||||
process.env.NODE_ENV === "production";
|
||||
export class AppEnvUtil {
|
||||
private constructor() {}
|
||||
|
||||
export const isTest = (): boolean =>
|
||||
process.env.NODE_ENV === "test";
|
||||
static get current(): AppEnv {
|
||||
const env = process.env.NEXT_PUBLIC_APP_ENV;
|
||||
if (env === "production" || env === "test") return env;
|
||||
return "development";
|
||||
}
|
||||
|
||||
static isDevelopment(): boolean {
|
||||
return AppEnvUtil.current === "development";
|
||||
}
|
||||
|
||||
static isProduction(): boolean {
|
||||
return AppEnvUtil.current === "production";
|
||||
}
|
||||
|
||||
static isTest(): boolean {
|
||||
return AppEnvUtil.current === "test";
|
||||
}
|
||||
|
||||
static canOutputLogs(): boolean {
|
||||
return !AppEnvUtil.isProduction();
|
||||
}
|
||||
}
|
||||
|
||||
+6
-6
@@ -1,22 +1,22 @@
|
||||
import pino, { type Logger as PinoLogger, type LoggerOptions } from "pino";
|
||||
|
||||
import { isProduction, isTest } from "./app-env";
|
||||
import { AppEnvUtil } from "./app-env";
|
||||
|
||||
/**
|
||||
* 全局 pino root logger(单例,进程级复用)。
|
||||
*
|
||||
* 配置驱动(基于 `app-env.ts` 的 `isProduction()` / `isTest()`):
|
||||
* - production: info 级别 + JSON(机器可解析,接入日志平台)
|
||||
* 配置驱动(基于 `app-env.ts` 的 `AppEnvUtil`):
|
||||
* - production: silent(不输出日志)
|
||||
* - test: warn 级别(减少 vitest 噪音)
|
||||
* - development: debug 级别 + ISO 时间戳(人眼友好)
|
||||
*/
|
||||
const rootLogger: PinoLogger = pino(createLoggerOptions());
|
||||
|
||||
function createLoggerOptions(): LoggerOptions {
|
||||
if (isProduction()) {
|
||||
return { level: "info" };
|
||||
if (!AppEnvUtil.canOutputLogs()) {
|
||||
return { level: "silent" };
|
||||
}
|
||||
if (isTest()) {
|
||||
if (AppEnvUtil.isTest()) {
|
||||
return { level: "warn" };
|
||||
}
|
||||
// development
|
||||
|
||||
Reference in New Issue
Block a user