Files
OmniRoute/src/shared/utils/logger.ts
Diego Rodrigues de Sa e Souza 1442c47bbb chore(release): v3.5.6 — email masking, model toggle, OpenRouter registries & bug fixes (#1080)
* fix(minimax): switch auth from x-api-key to Authorization Bearer (#1076)

Integrated into release/v3.5.6 — MiniMax auth fix with authHeader consistency normalization

* feat(CI,i18n): autogenerate language files + Add missing strings (#1071)

Integrated into release/v3.5.6 — i18n translations for memory, skills, and missing keys across 31 languages

* fix(ci): restore i18n continue-on-error, remove auto-commit race condition

* fix(husky): load nvm in hooks for VS Code compatibility

* fix(husky): gracefully skip hooks when npm is not in PATH

* fix: convert OpenAI function tool_choice to Claude tool format (#1072)

* fix: prevent EPIPE feedback loop filling logs at GB/s (#1006)

* fix: fallback to native fetch when undici dispatcher fails (#1054)

* fix: improve Qoder PAT validation with actionable error messages (#966)

- Add QODER_PERSONAL_ACCESS_TOKEN env var fallback for both validation and execution
- Pre-flight ping check to diagnose connectivity issues (Docker/proxy)
- Detect encrypted auth blobs from ~/.qoder/.auth/user and guide to website PAT
- Clear error messages for auth failures with link to integrations page
- Treat non-auth 4xx as auth-pass (request format issue, not token issue)
- Update tests to cover new validation paths (23 tests, all passing)

* feat: Improve the Chinese translation (#1079)

Integrated into release/v3.5.6

* chore(release): v3.5.6 — i18n updates and credential security fixes

* fix(ci): resolve e2e and docs-sync pipeline failures

* fix(security): bump next to 16.2.3 to resolve SNYK-JS-NEXT-15954202

* fix: guard Memory/Cache UI against null toLocaleString crash (#1083)

* fix: translate OpenAI tool_choice type 'function' to Claude 'tool' format (#1072)

* fix: pass custom baseUrl in provider API key validation (#1078)

* docs: update CHANGELOG with v3.5.6 bug fixes and security patches

* docs: rewrite implement-features workflow with 5-phase harvest-research-report-plan-execute pipeline

* docs: organize _ideia/ into viable/defer/notfit + add Phase 2.5 auto-response workflow

* docs: implementation plans for #1025, #750, #960, #1046 + close already-implemented #833, #973, #982

* feat: mask email addresses in dashboard for privacy (#1025)

* feat: add OpenRouter and GitHub to embedding/image provider registries (#960)

* feat: add model visibility toggle and search filter to provider page (#750)

* docs: move implemented features to notfit, update task plans status

* chore: untrack _ideia/ and _tasks/ from git — private/internal only

* chore(release): bump to v3.5.6 — changelog, docs, version sync & any-budget fix

* fix: remove explicit .ts extension in qoderCli import that caused 500 error in production build

---------

Co-authored-by: Jean Brito <jeanfbrito@gmail.com>
Co-authored-by: zenobit <zenobit@disroot.org>
Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
Co-authored-by: Ethan Hunt <136065060+only4copilot@users.noreply.github.com>
2026-04-09 15:55:59 -03:00

168 lines
4.9 KiB
TypeScript

/**
* Structured Logger — Pino-based logger for OmniRoute
*
* Usage:
* import { logger } from "@/shared/utils/logger";
* const log = logger.child({ module: "proxy" });
* log.info({ model: "gpt-4o" }, "Request received");
* log.error({ err }, "Connection failed");
*
* In development, output is pretty-printed via pino-pretty.
* In production, output is structured JSON for log aggregation.
*
* When APP_LOG_TO_FILE is enabled (default: true), logs are also written
* as JSON lines to the file specified by APP_LOG_FILE_PATH.
*/
import pino from "pino";
import { resolve } from "path";
import { getLogConfig, initLogRotation } from "@/lib/logRotation";
import { getAppLogLevel } from "@/lib/logEnv";
const isDev = process.env.NODE_ENV !== "production";
const baseConfig: pino.LoggerOptions = {
level: getAppLogLevel(isDev ? "debug" : "info"),
base: { service: "omniroute" },
timestamp: pino.stdTimeFunctions.isoTime,
formatters: {
level(label: string) {
return { level: label };
},
},
};
function getTransportCompatibleConfig(): pino.LoggerOptions {
const { formatters, ...rest } = baseConfig;
if (!formatters) return rest;
const { level: _levelFormatter, ...safeFormatters } = formatters;
return Object.keys(safeFormatters).length > 0 ? { ...rest, formatters: safeFormatters } : rest;
}
/**
* Build the logger with optional file transport.
* Uses pino transport targets for all destinations.
*/
function buildLogger(): pino.Logger {
const logConfig = getLogConfig();
const logLevel = (baseConfig.level as string) || "info";
const transportConfig = getTransportCompatibleConfig();
// If file logging is enabled, set up dual transport (stdout + file)
if (logConfig.logToFile) {
try {
// Initialize log directory and rotation
initLogRotation();
// Resolve to absolute path for pino worker threads
const absLogPath = resolve(logConfig.logFilePath);
if (isDev) {
// Dev: pino-pretty → stdout, JSON → file
return pino({
...transportConfig,
transport: {
targets: [
{
target: "pino-pretty",
options: {
colorize: true,
translateTime: "HH:MM:ss.l",
ignore: "pid,hostname,service",
messageFormat: "[{module}] {msg}",
destination: 1,
},
level: logLevel,
},
{
target: "pino/file",
options: { destination: absLogPath, mkdir: true },
level: logLevel,
},
],
},
});
}
// Production: JSON → stdout + JSON → file
return pino({
...transportConfig,
transport: {
targets: [
{
target: "pino/file",
options: { destination: 1 }, // stdout
level: logLevel,
},
{
target: "pino/file",
options: { destination: absLogPath, mkdir: true },
level: logLevel,
},
],
},
});
} catch (err) {
// Log the actual error for diagnostics (issue #165)
try {
process.stderr.write(
`[logger] Failed to set up file transport, attempting sync fallback: ${(err as Error)?.message || err}\n`
);
} catch {}
// Fallback: use sync pino.destination() instead of worker-thread transport
// pino.transport() uses worker threads which can fail in Next.js production bundles
try {
const absLogPath = resolve(logConfig.logFilePath);
const fileDestination = pino.destination({ dest: absLogPath, mkdir: true, sync: true });
// Production fallback: JSON to both stdout and file via multistream
return pino(
baseConfig,
pino.multistream([
{ stream: process.stdout, level: logLevel as pino.Level },
{ stream: fileDestination, level: logLevel as pino.Level },
])
);
} catch (fallbackErr) {
try {
process.stderr.write(
`[logger] Sync fallback also failed, falling back to console only: ${(fallbackErr as Error)?.message || fallbackErr}\n`
);
} catch {}
}
}
}
// Console-only (no file logging)
if (isDev) {
return pino({
...baseConfig,
transport: {
target: "pino-pretty",
options: {
colorize: true,
translateTime: "HH:MM:ss.l",
ignore: "pid,hostname,service",
messageFormat: "[{module}] {msg}",
},
},
});
}
return pino(baseConfig);
}
export const logger = buildLogger();
/**
* Create a child logger with a module tag.
* @param {string} module - Module name for log context (e.g., "proxy", "db", "sse")
* @returns {pino.Logger}
*/
export function createLogger(module: string) {
return logger.child({ module });
}
export default logger;