Open source file-system and knowledge based agent template. Build AI agents that stay up to date with your knowledge base
add @savoir/logger (based on logging-sucks)
Hugo Richard272cc859e143
diff --git a/apps/api/lib/logger.ts b/apps/api/lib/logger.tsnew file mode 100644index 0000000..c62f87b--- /dev/null+++ b/apps/api/lib/logger.ts@@ -0,0 +1,18 @@+import { createLogger, getLogger } from '@savoir/logger'++/**+ * Initialize the API logger+ * Call this once at application startup+ */+export function initLogger() {+ return createLogger({+ env: {+ service: 'api',+ environment: process.env.NODE_ENV ?? 'development',+ commitHash: process.env.COMMIT_SHA,+ version: '0.1.0',+ },+ })+}++export { getLogger }diff --git a/apps/api/middleware/logger.ts b/apps/api/middleware/logger.tsnew file mode 100644index 0000000..0ce6f36--- /dev/null+++ b/apps/api/middleware/logger.ts@@ -0,0 +1,72 @@+import { defineMiddleware, getRequestURL, type H3Event } from 'nitro/h3'+import { getLogger, type RequestLogger } from '@savoir/logger'++declare module 'nitro/h3' {+ interface H3EventContext {+ log: RequestLogger+ }+}++/** Paths to exclude from automatic logging (internal/health endpoints) */+const EXCLUDED_PATHS = [+ '/.well-known/',+ '/health',+ '/favicon.ico',+]++function getHttpMethod(event: H3Event): string {+ return (event as unknown as { method?: string }).method ?? 'GET'+}++function shouldLog(pathname: string): boolean {+ return !EXCLUDED_PATHS.some(excluded => pathname.startsWith(excluded))+}++/**+ * Request logging middleware+ * Creates a wide event logger for each request+ * Only emits logs for API endpoints (excludes internal workflow paths)+ */+export default defineMiddleware(async (event, next) => {+ const url = getRequestURL(event)+ const logger = getLogger()+ const shouldEmit = shouldLog(url.pathname)++ // Create request-scoped logger with initial context+ const log = logger.request({+ method: getHttpMethod(event),+ path: url.pathname,+ requestId: crypto.randomUUID(),+ })++ // Attach to event context for use in handlers+ event.context.log = log++ try {+ const response = await next()++ log.set({+ statusCode: 200,+ outcome: 'success',+ })++ return response+ }+ catch (error) {+ const statusCode = (error as { statusCode?: number }).statusCode ?? 500++ log.error(error as Error)+ log.set({+ statusCode,+ outcome: 'error',+ })++ throw error+ }+ finally {+ // Only emit logs for non-excluded paths, or always emit on errors+ if (shouldEmit || log.getContext().outcome === 'error') {+ log.emit()+ }+ }+})diff --git a/apps/api/package.json b/apps/api/package.jsonindex 10e828b..505d621 100644--- a/apps/api/package.json+++ b/apps/api/package.json@@ -13,6 +13,7 @@"lint:fix": "eslint . --fix"},"dependencies": {+ "@savoir/logger": "workspace:*","@types/node": "^25.0.9","giget": "^2.0.0","pathe": "^2.0.3",diff --git a/apps/api/plugins/logger.ts b/apps/api/plugins/logger.tsnew file mode 100644index 0000000..13d3613--- /dev/null+++ b/apps/api/plugins/logger.ts@@ -0,0 +1,9 @@+import { definePlugin } from 'nitro'+import { initLogger } from '~/lib/logger'++/**+ * Initialize the logger when the server starts+ */+export default definePlugin(() => {+ initLogger()+})diff --git a/apps/api/routes/api/sync/[source].post.ts b/apps/api/routes/api/sync/[source].post.tsindex f4ec9df..222e4a0 100644--- a/apps/api/routes/api/sync/[source].post.ts+++ b/apps/api/routes/api/sync/[source].post.ts@@ -71,33 +71,40 @@ export default defineHandler(async (event) => {await rm(resolve(syncDir, 'docs', outputPath), { recursive: true, force: true })}- console.log(`[sync] Syncing ${source.id}...`)+ const log = event.context.logconst result = await syncGitHubSource(source as GitHubSource, syncDir)- if (result.success) {- console.log(`[sync] ${source.id}: ${result.fileCount} files in ${result.duration}ms`)- } else {- console.error(`[sync] ${source.id} failed: ${result.error}`)- }-// Push to snapshot repository if enabledlet pushResult = nullif (shouldPush && result.success) {- console.log(`[sync] Pushing to ${config.snapshotRepo}...`)pushResult = await pushToSnapshot(syncDir, {repo: config.snapshotRepo,branch: config.snapshotBranch || 'main',token: config.githubToken,message: `chore: sync ${source.label} (${result.fileCount} files)`,})-- if (pushResult.success) {- console.log(`[sync] Pushed ${pushResult.filesChanged} files, commit: ${pushResult.commitSha}`)- } else {- console.error(`[sync] Push failed: ${pushResult.error}`)- }}+ log.set({+ source: {+ id: source.id,+ label: source.label,+ type: source.type,+ },+ sync: {+ success: result.success,+ fileCount: result.fileCount,+ syncDurationMs: result.duration,+ error: result.error,+ },+ push: pushResult ? {+ success: pushResult.success,+ filesChanged: pushResult.filesChanged,+ commitSha: pushResult.commitSha,+ error: pushResult.error,+ } : null,+ })+// Cleanup temp directoryawait rm(syncDir, { recursive: true, force: true }).catch(() => {})diff --git a/apps/api/routes/api/sync/index.post.ts b/apps/api/routes/api/sync/index.post.tsindex ba08609..e4a81e5 100644--- a/apps/api/routes/api/sync/index.post.ts+++ b/apps/api/routes/api/sync/index.post.ts@@ -55,16 +55,11 @@ export default defineHandler(async (event) => {const sources = getGitHubSources()const results: SyncResult[] = []+ const log = event.context.log+for (const source of sources) {- console.log(`[sync] Syncing ${source.id}...`)const result = await syncGitHubSource(source, syncDir)results.push(result)-- if (result.success) {- console.log(`[sync] ${source.id}: ${result.fileCount} files in ${result.duration}ms`)- } else {- console.error(`[sync] ${source.id} failed: ${result.error}`)- }}const successCount = results.filter((r) => r.success).length@@ -74,21 +69,28 @@ export default defineHandler(async (event) => {// Push to snapshot repository if enabledlet pushResult = nullif (shouldPush && successCount > 0) {- console.log(`[sync] Pushing to ${config.snapshotRepo}...`)pushResult = await pushToSnapshot(syncDir, {repo: config.snapshotRepo,branch: config.snapshotBranch || 'main',token: config.githubToken,message: `chore: sync ${successCount} sources (${totalFiles} files)`,})-- if (pushResult.success) {- console.log(`[sync] Pushed ${pushResult.filesChanged} files, commit: ${pushResult.commitSha}`)- } else {- console.error(`[sync] Push failed: ${pushResult.error}`)- }}+ log.set({+ sync: {+ sourcesTotal: sources.length,+ sourcesSuccess: successCount,+ sourcesFailed: failCount,+ filesTotal: totalFiles,+ },+ push: pushResult ? {+ success: pushResult.success,+ filesChanged: pushResult.filesChanged,+ commitSha: pushResult.commitSha,+ } : null,+ })+// Cleanup temp directoryawait rm(syncDir, { recursive: true, force: true }).catch(() => {})diff --git a/apps/api/workflows/sync-docs/steps/cleanup.ts b/apps/api/workflows/sync-docs/steps/cleanup.tsindex 781c9f8..911d9d2 100644--- a/apps/api/workflows/sync-docs/steps/cleanup.ts+++ b/apps/api/workflows/sync-docs/steps/cleanup.ts@@ -1,12 +1,15 @@import { rm } from 'node:fs/promises'+import { getLogger } from '@savoir/logger'export async function cleanupWorkspace(syncDir: string): Promise<void> {'use step'+ const logger = getLogger()+try {await rm(syncDir, { recursive: true, force: true })- console.log('[workflow] Workspace cleaned up')+ logger.log('sync', 'Workspace cleaned up')} catch {- console.warn('[workflow] Failed to cleanup workspace')+ logger.log('sync', 'Failed to cleanup workspace')}}diff --git a/apps/api/workflows/sync-docs/steps/get-sources.ts b/apps/api/workflows/sync-docs/steps/get-sources.tsindex 83f5218..670c361 100644--- a/apps/api/workflows/sync-docs/steps/get-sources.ts+++ b/apps/api/workflows/sync-docs/steps/get-sources.ts@@ -1,3 +1,4 @@+import { getLogger } from '@savoir/logger'import { FatalError } from 'workflow'import type { GitHubSource } from '../utils/index.js'import { getGitHubSources, getSourceById } from '../utils/index.js'@@ -5,6 +6,7 @@ import { getGitHubSources, getSourceById } from '../utils/index.js'export async function getSourcesToSync(sourceFilter?: string): Promise<GitHubSource[]> {'use step'+ const logger = getLogger()let sources = getGitHubSources()if (sourceFilter) {@@ -15,6 +17,6 @@ export async function getSourcesToSync(sourceFilter?: string): Promise<GitHubSousources = [source as GitHubSource]}- console.log(`[workflow] Found ${sources.length} source(s) to sync`)+ logger.log('sync', `Found ${sources.length} source(s) to sync`)return sources}diff --git a/apps/api/workflows/sync-docs/steps/prepare-workspace.ts b/apps/api/workflows/sync-docs/steps/prepare-workspace.tsindex 86f7e0d..09ad47d 100644--- a/apps/api/workflows/sync-docs/steps/prepare-workspace.ts+++ b/apps/api/workflows/sync-docs/steps/prepare-workspace.ts@@ -1,10 +1,12 @@import { mkdir, rm } from 'node:fs/promises'import { tmpdir } from 'node:os'import { resolve } from 'pathe'+import { getLogger } from '@savoir/logger'export async function prepareWorkspace(reset: boolean): Promise<string> {'use step'+ const logger = getLogger()const syncDir = resolve(tmpdir(), 'savoir-sync', Date.now().toString())await mkdir(syncDir, { recursive: true })@@ -13,7 +15,7 @@ export async function prepareWorkspace(reset: boolean): Promise<string> {}await mkdir(resolve(syncDir, 'docs'), { recursive: true })- console.log(`[workflow] Workspace ready: ${syncDir}`)+ logger.log('sync', `Workspace ready: ${syncDir}`)return syncDir}diff --git a/apps/api/workflows/sync-docs/steps/push-snapshot.ts b/apps/api/workflows/sync-docs/steps/push-snapshot.tsindex 66c5cab..a0b89ff 100644--- a/apps/api/workflows/sync-docs/steps/push-snapshot.ts+++ b/apps/api/workflows/sync-docs/steps/push-snapshot.ts@@ -1,3 +1,4 @@+import { getLogger } from '@savoir/logger'import type { SyncConfig } from '../utils/index.js'import { pushToSnapshot } from '../utils/index.js'@@ -9,7 +10,8 @@ export async function pushToSnapshotStep(): Promise<{ success: boolean; commitSha?: string; error?: string }> {'use step'- console.log(`[workflow] Pushing to ${config.snapshotRepo}...`)+ const logger = getLogger()+ logger.log('sync', `Pushing to ${config.snapshotRepo}...`)const result = await pushToSnapshot(syncDir, {repo: config.snapshotRepo,@@ -19,7 +21,7 @@ export async function pushToSnapshotStep(})if (result.success) {- console.log(`[workflow] Pushed ${result.filesChanged} files, commit: ${result.commitSha}`)+ logger.log('sync', `Pushed ${result.filesChanged} files, commit: ${result.commitSha}`)} else {throw new Error(`Push failed: ${result.error}`)}diff --git a/apps/api/workflows/sync-docs/steps/sync-source.ts b/apps/api/workflows/sync-docs/steps/sync-source.tsindex 4d31199..f01b5a8 100644--- a/apps/api/workflows/sync-docs/steps/sync-source.ts+++ b/apps/api/workflows/sync-docs/steps/sync-source.ts@@ -1,19 +1,26 @@+import { getLogger } from '@savoir/logger'import type { GitHubSource, SyncResult } from '../utils/index.js'import { syncGitHubSource } from '../utils/index.js'+function formatDuration(ms: number): string {+ return ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(2)}s`+}+export async function syncSingleSource(source: GitHubSource,syncDir: string): Promise<SyncResult> {'use step'- console.log(`[workflow] Syncing ${source.id}...`)+ const logger = getLogger()+ logger.log('sync', `Syncing ${source.id}...`)+const result = await syncGitHubSource(source, syncDir)if (result.success) {- console.log(`[workflow] ${source.id}: ${result.fileCount} files in ${result.duration}ms`)+ logger.log('sync', `${source.id}: ${result.fileCount} files in ${formatDuration(result.duration)}`)} else {- console.error(`[workflow] ${source.id} failed: ${result.error}`)+ logger.error({ source: source.id, error: result.error, message: 'Sync failed' })throw new Error(`Failed to sync ${source.id}: ${result.error}`)}diff --git a/apps/api/workflows/sync-docs/workflow.ts b/apps/api/workflows/sync-docs/workflow.tsindex 436115f..8097a27 100644--- a/apps/api/workflows/sync-docs/workflow.ts+++ b/apps/api/workflows/sync-docs/workflow.ts@@ -1,3 +1,4 @@+import { getLogger } from '@savoir/logger'import { FatalError } from 'workflow'import type { SyncResult, SyncConfig, SyncOptions } from './utils/index.js'import {@@ -63,6 +64,11 @@ export async function syncDocumentation(await cleanupWorkspace(syncDir)+ // Log summary+ const logger = getLogger()+ const status = failCount === 0 ? '✓' : '✗'+ logger.log('sync', `${status} Done: ${successCount}/${sources.length} sources, ${totalFiles} files`)+return {success: failCount === 0 && (!push || pushResult?.success !== false),summary: {diff --git a/package.json b/package.jsonindex 3baeeae..3432f0c 100644--- a/package.json+++ b/package.json@@ -13,6 +13,7 @@"url": "https://github.com/HugoRCD/savoir/issues"},"scripts": {+ "prepare": "turbo build --filter='./packages/*'","build": "turbo build","dev": "turbo dev","dev:api": "pnpm --filter @savoir/api dev",diff --git a/packages/logger/package.json b/packages/logger/package.jsonnew file mode 100644index 0000000..02307cb--- /dev/null+++ b/packages/logger/package.json@@ -0,0 +1,38 @@+{+ "name": "@savoir/logger",+ "version": "0.0.1",+ "description": "Logging utilities with context and timing support",+ "type": "module",+ "exports": {+ ".": {+ "import": {+ "types": "./dist/index.d.ts",+ "default": "./dist/index.js"+ },+ "require": {+ "types": "./dist/index.d.cts",+ "default": "./dist/index.cjs"+ }+ }+ },+ "main": "./dist/index.cjs",+ "module": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "sideEffects": false,+ "files": [+ "dist"+ ],+ "scripts": {+ "build": "tsdown",+ "dev": "tsdown --watch",+ "typecheck": "tsc --noEmit",+ "lint": "eslint .",+ "lint:fix": "eslint . --fix",+ "prepublishOnly": "pnpm build"+ },+ "devDependencies": {+ "@types/node": "^22.15.21",+ "tsdown": "^0.12.4",+ "typescript": "^5.8.3"+ }+}diff --git a/packages/logger/src/error.ts b/packages/logger/src/error.tsnew file mode 100644index 0000000..6ec0eb3--- /dev/null+++ b/packages/logger/src/error.ts@@ -0,0 +1,106 @@+export interface ErrorOptions {+ /** What actually happened */+ message: string+ /** Why this error occurred */+ why?: string+ /** How to fix this issue */+ fix?: string+ /** Link to documentation or more information */+ link?: string+ /** The original error that caused this */+ cause?: Error+}++/**+ * Structured error with context for better debugging+ *+ * @example+ * ```ts+ * throw new SavoirError({+ * message: 'Failed to sync repository',+ * why: 'GitHub API rate limit exceeded',+ * fix: 'Wait 1 hour or use a different token',+ * link: 'https://docs.github.com/en/rest/rate-limit',+ * cause: originalError,+ * })+ * ```+ */+export class SavoirError extends Error {+ readonly why?: string+ readonly fix?: string+ readonly link?: string++ constructor(options: ErrorOptions | string) {+ const opts = typeof options === 'string' ? { message: options } : options++ super(opts.message, { cause: opts.cause })++ this.name = 'SavoirError'+ this.why = opts.why+ this.fix = opts.fix+ this.link = opts.link++ // Maintain proper stack trace in V8+ if (Error.captureStackTrace) {+ Error.captureStackTrace(this, SavoirError)+ }+ }++ /**+ * Format error for console output with colors+ */+ toString(): string {+ const red = '\x1b[31m'+ const yellow = '\x1b[33m'+ const cyan = '\x1b[36m'+ const dim = '\x1b[2m'+ const reset = '\x1b[0m'+ const bold = '\x1b[1m'++ const lines: string[] = []++ lines.push(`${red}${bold}Error:${reset} ${this.message}`)++ if (this.why) {+ lines.push(`${yellow}Why:${reset} ${this.why}`)+ }++ if (this.fix) {+ lines.push(`${cyan}Fix:${reset} ${this.fix}`)+ }++ if (this.link) {+ lines.push(`${dim}More info:${reset} ${this.link}`)+ }++ if (this.cause) {+ lines.push(`${dim}Caused by:${reset} ${(this.cause as Error).message}`)+ }++ return lines.join('\n')+ }++ /**+ * Convert to plain object for JSON serialization+ */+ toJSON(): Record<string, unknown> {+ return {+ name: this.name,+ message: this.message,+ why: this.why,+ fix: this.fix,+ link: this.link,+ cause: this.cause instanceof Error+ ? { name: this.cause.name, message: this.cause.message }+ : undefined,+ stack: this.stack,+ }+ }+}++/**+ * Create a SavoirError (functional alternative to `new SavoirError()`)+ */+export function createError(options: ErrorOptions | string): SavoirError {+ return new SavoirError(options)+}diff --git a/packages/logger/src/index.ts b/packages/logger/src/index.tsnew file mode 100644index 0000000..56f825c--- /dev/null+++ b/packages/logger/src/index.ts@@ -0,0 +1,12 @@+export { createLogger, getLogger, resetLogger } from './logger'+export { SavoirError, createError } from './error'+export type { ErrorOptions } from './error'+export type {+ BaseWideEvent,+ EnvironmentContext,+ Logger,+ LoggerConfig,+ RequestLogger,+ WideEvent,+ WideEventBuilder,+} from './types'diff --git a/packages/logger/src/logger.ts b/packages/logger/src/logger.tsnew file mode 100644index 0000000..23c2dcb--- /dev/null+++ b/packages/logger/src/logger.ts@@ -0,0 +1,187 @@+import type { EnvironmentContext, Logger, LoggerConfig, RequestLogger, WideEvent } from './types'++let globalLogger: Logger | null = null++/**+ * Format duration in human-readable format+ * - < 1s: shows milliseconds (e.g., "42ms")+ * - >= 1s: shows seconds (e.g., "1.5s")+ */+function formatDuration(ms: number): string {+ if (ms < 1000) {+ return `${Math.round(ms)}ms`+ }+ return `${(ms / 1000).toFixed(2)}s`+}++/**+ * Create the application logger (singleton)+ *+ * @example+ * ```ts+ * const logger = createLogger({+ * env: {+ * service: 'api',+ * environment: process.env.NODE_ENV ?? 'development',+ * },+ * })+ *+ * // Simple workflow-style logs+ * logger.log('workflow', 'Syncing nuxt-icon...')+ * logger.log('workflow', 'nuxt-icon: 1 files in 31ms')+ *+ * // Wide event for request logging+ * const log = logger.request({ method: 'POST', path: '/checkout' })+ * log.set({ user: { id: '123' } })+ * log.emit()+ * ```+ */+export function createLogger(config: LoggerConfig): Logger {+ if (globalLogger) {+ return globalLogger+ }++ const { env, pretty = process.env.NODE_ENV !== 'production' } = config++ function formatEvent(level: 'info' | 'error', event: Record<string, unknown>): WideEvent {+ return {+ timestamp: new Date().toISOString(),+ level,+ service: env.service,+ environment: env.environment,+ ...(env.commitHash && { commitHash: env.commitHash }),+ ...(env.version && { version: env.version }),+ ...(env.region && { region: env.region }),+ ...event,+ }+ }++ function emitWideEvent(level: 'info' | 'error', event: Record<string, unknown>): void {+ const formatted = formatEvent(level, event)++ if (pretty) {+ const { timestamp, level: lvl, service, ...rest } = formatted+ const color = lvl === 'error' ? '\x1b[31m' : '\x1b[36m'+ const reset = '\x1b[0m'+ const dim = '\x1b[2m'++ console[lvl === 'error' ? 'error' : 'log'](+ `${dim}${timestamp}${reset} ${color}[${service}]${reset}`,+ JSON.stringify(rest, null, 2),+ )+ }+ else {+ console[level === 'error' ? 'error' : 'log'](JSON.stringify(formatted))+ }+ }++ /**+ * Simple log output: [tag] message+ * For workflow-style progress messages+ */+ function log(tag: string, message: string): void {+ const cyan = '\x1b[36m'+ const reset = '\x1b[0m'++ if (pretty) {+ console.log(`${cyan}[${tag}]${reset} ${message}`)+ }+ else {+ console.log(JSON.stringify({+ timestamp: new Date().toISOString(),+ level: 'info',+ service: env.service,+ tag,+ message,+ }))+ }+ }++ function createRequestLogger(initialContext: Record<string, unknown> = {}): RequestLogger {+ const startTime = performance.now()+ let context: Record<string, unknown> = { ...initialContext }+ let errorInfo: Record<string, unknown> | null = null++ return {+ set<T extends Record<string, unknown>>(newContext: T): void {+ context = { ...context, ...newContext }+ },++ error(error: Error | string, extraContext?: Record<string, unknown>): void {+ if (error instanceof Error) {+ errorInfo = {+ message: error.message,+ name: error.name,+ ...(error.stack && { stack: error.stack }),+ ...extraContext,+ }+ }+ else {+ errorInfo = { message: error, ...extraContext }+ }+ },++ emit(overrides?: Record<string, unknown>): void {+ const durationMs = performance.now() - startTime+ const level = errorInfo ? 'error' : 'info'++ emitWideEvent(level, {+ ...context,+ ...(errorInfo && { error: errorInfo }),+ ...overrides,+ duration: formatDuration(durationMs),+ durationMs: Math.round(durationMs * 100) / 100,+ })+ },++ getContext(): Record<string, unknown> {+ return { ...context }+ },+ }+ }++ globalLogger = {+ log,++ info(event: Record<string, unknown>): void {+ emitWideEvent('info', event)+ },++ error(event: Record<string, unknown>): void {+ emitWideEvent('error', event)+ },++ request: createRequestLogger,++ get env(): EnvironmentContext {+ return env+ },+ }++ return globalLogger+}++/**+ * Get the global logger instance+ * Auto-initializes with defaults if not already initialized+ */+export function getLogger(): Logger {+ if (!globalLogger) {+ createLogger({+ env: {+ service: process.env.SERVICE_NAME ?? 'app',+ environment: process.env.NODE_ENV ?? 'development',+ commitHash: process.env.COMMIT_SHA,+ version: process.env.npm_package_version,+ },+ })+ }+ return globalLogger!+}++/**+ * Reset the global logger (useful for testing)+ */+export function resetLogger(): void {+ globalLogger = null+}diff --git a/packages/logger/src/types.ts b/packages/logger/src/types.tsnew file mode 100644index 0000000..ca9018f--- /dev/null+++ b/packages/logger/src/types.ts@@ -0,0 +1,92 @@+/**+ * Environment context automatically included in every log event+ */+export interface EnvironmentContext {+ /** Service name (e.g., 'api', 'worker') */+ service: string+ /** Environment (e.g., 'production', 'staging', 'development') */+ environment: string+ /** Git commit hash for deployment tracking */+ commitHash?: string+ /** Service version */+ version?: string+ /** Region/datacenter identifier */+ region?: string+}++/**+ * Configuration options for the logger+ */+export interface LoggerConfig {+ /** Environment context included in all events */+ env: EnvironmentContext+ /** Enable pretty printing for development (default: based on NODE_ENV) */+ pretty?: boolean+}++/**+ * Base fields for all wide events+ */+export interface BaseWideEvent {+ /** ISO timestamp */+ timestamp: string+ /** Log level */+ level: 'info' | 'error'+ /** Service name */+ service: string+ /** Environment */+ environment: string+ /** Commit hash */+ commitHash?: string+ /** Service version */+ version?: string+ /** Region */+ region?: string+}++/**+ * A wide event with arbitrary additional context+ */+export type WideEvent = BaseWideEvent & Record<string, unknown>++/**+ * Context builder for accumulating wide event data+ */+export interface WideEventBuilder {+ /** Add context to the wide event */+ set: <T extends Record<string, unknown>>(context: T) => void+ /** Get current accumulated context */+ getContext: () => Record<string, unknown>+ /** Emit the wide event (called automatically in finally block) */+ emit: (level?: 'info' | 'error') => void+}++/**+ * Request-scoped logger for building wide events+ */+export interface RequestLogger {+ /** Add context to the current request's wide event */+ set: <T extends Record<string, unknown>>(context: T) => void+ /** Log an error (will be included in the wide event) */+ error: (error: Error | string, context?: Record<string, unknown>) => void+ /** Manually emit the wide event (usually done by middleware) */+ emit: (overrides?: Record<string, unknown>) => void+ /** Get the accumulated context */+ getContext: () => Record<string, unknown>+}++/**+ * Main logger interface - single instance per application+ */+export interface Logger {+ /** Simple log: [tag] message - for workflow-style progress logs */+ log: (tag: string, message: string) => void+ /** Log an info-level wide event */+ info: (event: Record<string, unknown>) => void+ /** Log an error-level wide event */+ error: (event: Record<string, unknown>) => void+ /** Create a request-scoped logger for building a wide event */+ request: (initialContext?: Record<string, unknown>) => RequestLogger+ /** Get environment context */+ readonly env: EnvironmentContext+}diff --git a/packages/logger/tsconfig.json b/packages/logger/tsconfig.jsonnew file mode 100644index 0000000..cb6ef60--- /dev/null+++ b/packages/logger/tsconfig.json@@ -0,0 +1,13 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "Bundler",+ "strict": true,+ "declaration": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "noEmit": true+ },+ "include": ["src"]+}diff --git a/packages/logger/tsdown.config.ts b/packages/logger/tsdown.config.tsnew file mode 100644index 0000000..03c2d29--- /dev/null+++ b/packages/logger/tsdown.config.ts@@ -0,0 +1,11 @@+import { defineConfig } from 'tsdown'++export default defineConfig({+ entry: ['src/index.ts'],+ format: ['esm'],+ dts: {+ sourcemap: false,+ },+ clean: true,+ hash: false,+})diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 645d4ae..fc5a327 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -20,6 +20,9 @@ importers:apps/api:dependencies:+ '@savoir/logger':+ specifier: workspace:*+ version: link:../../packages/logger'@types/node':specifier: ^25.0.9version: 25.0.9@@ -46,6 +49,18 @@ importers:specifier: ^5.8.3version: 5.9.3+ packages/logger:+ devDependencies:+ '@types/node':+ specifier: ^22.15.21+ version: 22.19.7+ tsdown:+ specifier: ^0.12.4+ version: 0.12.9([email protected])+ typescript:+ specifier: ^5.8.3+ version: 5.9.3+packages:'@altano/[email protected]':@@ -182,14 +197,31 @@ packages:resolution: {integrity: sha512-JYgintcMjRiCvS8mMECzaEn+m3PfoQiyqukOMCCVQtoJGYJw8j/8LBJEiqkHLkfwCcs74E3pbAUFNg7d9VNJ+Q==}engines: {node: '>=6.9.0'}+ '@babel/[email protected]':+ resolution: {integrity: sha512-lOoVRwADj8hjf7al89tvQ2a1lf53Z+7tiXMgpZJL3maQPDxh0DgLMN62B2MKUOFcoodBHLMbDM6WAbKgNy5Suw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==}+ engines: {node: '>=6.9.0'}+'@babel/[email protected]':resolution: {integrity: sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==}engines: {node: '>=6.9.0'}+ '@babel/[email protected]':+ resolution: {integrity: sha512-TeR9zWR18BvbfPmGbLampPMW+uW1NZnJlRuuHso8i87QZNq2JRF9i6RgxRqtEq+wQGsS19NNTWr2duhnE49mfQ==}+ engines: {node: '>=6.0.0'}+ hasBin: true+'@babel/[email protected]':resolution: {integrity: sha512-05WQkdpL9COIMz4LjTxGpPNCdlpyimKppYNoJ5Di5EUObifl8t4tuLuUBBZEpoLYOmfvIWrsp9fCl0HoPRVTdA==}engines: {node: '>=6.9.0'}+ '@babel/[email protected]':+ resolution: {integrity: sha512-0ZrskXVEHSWIqZM/sQZ4EV3jZJXRkio/WCxaqKZP1g//CEWEPSfeZFcms4XeKBCHU0ZKnIkdJeU/kF+eRp5lBg==}+ engines: {node: '>=6.9.0'}+'@emnapi/[email protected]':resolution: {integrity: sha512-AvT9QFpxK0Zd8J0jopedNm+w/2fIzvtPKPjqyw9jwvBaReTTqPBk9Hixaz7KbjimP+QNz605/XnjFcDAL2pqBg==}@@ -937,6 +969,9 @@ packages:resolution: {integrity: sha512-WYa2tUVV5HiArWPB3ydlOc4R2ivq0IDrlqhMi3l7mVsFEXNcTfxYFPIHXHXIh/ca/y/V5N4E1zecyxdIBjYnkQ==}engines: {node: '>= 10.0.0'}+ '@quansync/[email protected]':+ resolution: {integrity: sha512-4TJ3DFtlf1L5LDMaM6CanJ/0lckGNtJcMjQ1NAV6zDmA0tEHKZtxNKin8EgPaVX1YzljbxckyT2tJrpQKAtngQ==}+'@rolldown/[email protected]':resolution: {integrity: sha512-hOW6iQXtpG4uCW1zGK56+KhEXGttSkTp2ykncW/nkOIF/jOKTqbM944Q73HVeMXP1mPRvE2cZwNp3xeLIeyIGQ==}engines: {node: ^20.19.0 || >=22.12.0}@@ -1293,6 +1328,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==}+ '@types/[email protected]':+ resolution: {integrity: sha512-MciR4AKGHWl7xwxkBa6xUGxQJ4VBOmPTF7sL+iGzuahOFaO0jHCsuEfS80pan1ef4gWId1oWOweIhrDEYLuaOw==}+'@types/[email protected]':resolution: {integrity: sha512-/rpCXHlCWeqClNBwUhDcusJxXYDjZTyE8v5oTO7WbL8eij2nKhUeU89/6xgjU7N4/Vh3He0BtyhJdQbDyhiXAw==}@@ -1592,6 +1630,10 @@ packages:resolution: {integrity: sha512-0qWUglt9JEqLFr3w1I1pbrChn1grhaiAR2ocX1PP/flRmxgtwTzPFFFnfIlD6aMOLQZgSuCRlidD70lvx8yhzg==}engines: {node: '>=14'}+ resolution: {integrity: sha512-HqZ5rWlFjGiV0tDm3UxxgNRqsOTniqoKZu0pIAfh7TZQMGuZK+hH0drySty0si0QXj1ieop4+SkSfPZBPPkHig==}+ engines: {node: '>=14'}+resolution: {integrity: sha512-ixiS0nLNNG5jNQzgZJNoUpBKdo9yTYZMGJ+QgT2jmjR7G7+QHRCc4v6LQ3NgE7EBJq+o0ams3waJwkrlBom8Ig==}engines: {node: '>=14'}@@ -1603,6 +1645,10 @@ packages:resolution: {integrity: sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==}engines: {node: '>=8'}+ resolution: {integrity: sha512-m1Q/RaVOnTp9JxPX+F+Zn7IcLYMzM8kZofDImfsKZd8MbR+ikdOzTeztStWqfrqIxZnYWryyI9ePm3NGjnZgGw==}+ engines: {node: '>=20.19.0'}+resolution: {integrity: sha512-tLRNUXati5MFePdAk8dw7Qt7DpxPB60ofAgn8WRhW6a2rcimZnYBP9oxHiv0OHy+Wz7kPMG+t4LGdt31+4EmGg==}@@ -1616,6 +1662,9 @@ packages:resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}+ resolution: {integrity: sha512-KrayHS5pBi69Xi9JmvoqrIgYGDkD6mcSe/i6YKi3w5kekCLzrX4+nawcXqrj2tIp50Kw/mT/s3p+GVK0A0sKxw==}+resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==}@@ -1652,6 +1701,10 @@ packages:magicast:optional: true+ resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==}+ engines: {node: '>=8'}+resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==}engines: {node: '>=6'}@@ -1856,6 +1909,10 @@ packages:resolution: {integrity: sha512-k1gCAXAsNgLwEL+Y8Wvl+M6oEFj5bgazfZULpS5CneoPPXRaCCW7dm+q21Ky2VEE5X+VeRDBVg1Pcvvsr4TtNQ==}engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0}+ resolution: {integrity: sha512-qejHi7bcSD4hQAZE0tNAawRK1ZtafHDmMTMkrrIGgSLl7hTnQHmKCeB45xAcbfTqK2zowkM3j3bHt/4b/ARbYQ==}+ engines: {node: '>=0.3.1'}+resolution: {integrity: sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==}engines: {node: '>=8'}@@ -1868,6 +1925,15 @@ packages:resolution: {integrity: sha512-JVUnt+DUIzu87TABbhPmNfVdBDt18BLOWjMUFJMSi/Qqg7NTYtabbvSNJGOJ7afbRuv9D/lngizHtP7QyLQ+9w==}engines: {node: '>=12'}+ resolution: {integrity: sha512-bihc7jPC90VrosXNzK0LTE2cuLP6jr0Ro8jk+kMugHReJVLIpHz/xadeq3MhuwyO4TD4OA3L1Q8pBBFRc08Tsw==}+ engines: {node: '>=20.19.0'}+ peerDependencies:+ oxc-resolver: '>=11.0.0'+ peerDependenciesMeta:+ oxc-resolver:+ optional: true+resolution: {integrity: sha512-OFzVOv03YpvtcWGe5AayU5G2hgybsg3iqA6drU8UaoZyB9jLGMTrz9+asnLp/E+6qPh88yEI1gvyZFZ41dmgww==}@@ -1882,6 +1948,10 @@ packages:resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==}+ resolution: {integrity: sha512-i6UzDscO/XfAcNYD75CfICkmfLedpyPDdozrLMmQc5ORaQcdMoc21OnlEylMIqI7U8eniKrPMxxtj8k0vhmJhA==}+ engines: {node: '>=14'}+resolution: {integrity: sha512-6Jw4sE1maoRJo3q8MsSIn2onJFbLTOjY9hlx4DZXmOKvLRd1Ok2kXmAGXaafL2+ijsJZ1ClYbl/pmqr9+k4iUQ==}engines: {node: '>=10.13.0'}@@ -2180,6 +2250,9 @@ packages:resolution: {integrity: sha512-CsNUt5x9LUdx6hnk/E2SZLsDyvfqANZSUq4+D3D8RzDJ2M+HDTIkF60ibS1vHaK55vzgiZw1bEPFG9yH7l33wA==}engines: {node: '>=12'}+ resolution: {integrity: sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==}+resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==}engines: {node: '>= 4'}@@ -2281,6 +2354,11 @@ packages:resolution: {integrity: sha512-Hicd6JK5Njt2QB6XYFS7ok9e37O8AYk3jTcppG4YVQnYjOemymvTcmc7OWsmq/Qqj5TdRFO5/x/tIPmBeRtGHg==}engines: {node: '>=12.0.0'}+ resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==}+ engines: {node: '>=6'}+ hasBin: true+resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==}@@ -2601,6 +2679,9 @@ packages:resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}engines: {node: '>=6'}+ resolution: {integrity: sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA==}+resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}@@ -2643,6 +2724,22 @@ packages:resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==}engines: {iojs: '>=1.0.0', node: '>=0.10.0'}+ resolution: {integrity: sha512-wjNhHZz9dlN6PTIXyizB6u/mAg1wEFMW9yw7imEVe3CxHSRnNHVyycIX0yDEOVJfDNISLPbkCIPEpFpizy5+PQ==}+ engines: {node: '>=20.18.0'}+ peerDependencies:+ '@typescript/native-preview': '>=7.0.0-dev.20250601.1'+ rolldown: ^1.0.0-beta.9+ typescript: ^5.0.0+ vue-tsc: ^2.2.0 || ^3.0.0+ peerDependenciesMeta:+ '@typescript/native-preview':+ optional: true+ typescript:+ optional: true+ vue-tsc:+ optional: true+resolution: {integrity: sha512-YYgpv7MiTp9LdLj1fzGzCtij8Yi2OKEc3HQtfbIxW4yuSgpQz9518I69U72T5ErPA/ATOXqlcisiLrWy+5V9YA==}engines: {node: ^20.19.0 || >=22.12.0}@@ -2811,6 +2908,28 @@ packages:peerDependencies:typescript: '>=4.8.4'+ resolution: {integrity: sha512-MfrXm9PIlT3saovtWKf/gCJJ/NQCdE0SiREkdNC+9Qy6UHhdeDPxnkFaBD7xttVUmgp0yUHtGirpoLB+OVLuLA==}+ engines: {node: '>=18.0.0'}+ hasBin: true+ peerDependencies:+ '@arethetypeswrong/core': ^0.18.1+ publint: ^0.3.0+ typescript: ^5.0.0+ unplugin-lightningcss: ^0.4.0+ unplugin-unused: ^0.5.0+ peerDependenciesMeta:+ '@arethetypeswrong/core':+ optional: true+ publint:+ optional: true+ typescript:+ optional: true+ unplugin-lightningcss:+ optional: true+ unplugin-unused:+ optional: true+resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}@@ -2876,9 +2995,18 @@ packages:resolution: {integrity: sha512-dPJyqPzx8preQhqq24bBG1YNkvigm87K8kVEHCD+ruZg24t6IFEFv00xMWfxcC4djmFtiTLdFuADn4+DOz6R7Q==}hasBin: true+ resolution: {integrity: sha512-VgPCvLWugINbXvMQDf8Jh0mlbvNjNC6eSUziHsBCMpxR05OPrNrvDnyatdMjRgcHaaNsCqz+wjNXxNw1kRLHUg==}++ resolution: {integrity: sha512-nrMlWRQ1xdTjSnSUqvYqJzbTBFugoqHobQj58B2bc8qxHKBBHMNNsWQFP3Cd3/JZK907voM2geYPWqD4VK3MPQ==}+resolution: {integrity: sha512-p+Rz9x0R7X+CYDkT+Xg8/GhpcShTlU8n+cf9OtOEf7zEQsNcCZO1dPKNRDqvUTaq+P32PMMkxWHwfrxkqfqAYg==}+ resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}+resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==}@@ -3490,10 +3618,29 @@ snapshots:js-tokens: 4.0.0picocolors: 1.1.1+ '@babel/[email protected]':+ dependencies:+ '@babel/parser': 7.28.6+ '@babel/types': 7.28.6+ '@jridgewell/gen-mapping': 0.3.13+ '@jridgewell/trace-mapping': 0.3.31+ jsesc: 3.1.0++ '@babel/[email protected]': {}+'@babel/[email protected]': {}+ '@babel/[email protected]':+ dependencies:+ '@babel/types': 7.28.6+'@babel/[email protected]': {}+ '@babel/[email protected]':+ dependencies:+ '@babel/helper-string-parser': 7.27.1+ '@babel/helper-validator-identifier': 7.28.5+'@emnapi/[email protected]':dependencies:'@emnapi/wasi-threads': 1.1.0@@ -4079,6 +4226,10 @@ snapshots:'@parcel/watcher-win32-ia32': 2.5.4'@parcel/watcher-win32-x64': 2.5.4+ '@quansync/[email protected]':+ dependencies:+ quansync: 1.0.0+'@rolldown/[email protected]':optional: true@@ -4476,6 +4627,10 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]':+ dependencies:+ undici-types: 6.21.0+'@types/[email protected]':dependencies:undici-types: 7.16.0@@ -4906,12 +5061,19 @@ snapshots:+ [email protected]: {}++ dependencies:+ '@babel/parser': 7.28.6+ pathe: 2.0.3+@@ -4940,6 +5102,8 @@ snapshots:+ [email protected]: {}+@@ -4989,6 +5153,8 @@ snapshots:pkg-types: 2.3.0rc9: 2.1.2+ [email protected]: {}+@@ -5128,6 +5294,8 @@ snapshots:+ [email protected]: {}+dependencies:path-type: 4.0.0@@ -5136,6 +5304,8 @@ snapshots:+ [email protected]: {}+dependencies:ansi-regex: 5.0.1@@ -5150,6 +5320,8 @@ snapshots:+ [email protected]: {}+dependencies:graceful-fs: 4.2.11@@ -5523,6 +5695,8 @@ snapshots:+ [email protected]: {}+@@ -5590,6 +5764,8 @@ snapshots:+ [email protected]: {}+@@ -5957,6 +6133,8 @@ snapshots:+ [email protected]: {}+@@ -5988,6 +6166,23 @@ snapshots:+ dependencies:+ '@babel/generator': 7.28.6+ '@babel/parser': 7.28.6+ '@babel/types': 7.28.6+ ast-kit: 2.2.0+ birpc: 2.9.0+ debug: 4.4.3([email protected])+ dts-resolver: 2.1.3+ get-tsconfig: 4.13.0+ rolldown: 1.0.0-beta.60+ optionalDependencies:+ typescript: 5.9.3+ transitivePeerDependencies:+ - oxc-resolver+ - supports-color+dependencies:'@oxc-project/types': 0.108.0@@ -6167,6 +6362,29 @@ snapshots:dependencies:typescript: 5.9.3+ dependencies:+ ansis: 4.2.0+ cac: 6.7.14+ chokidar: 4.0.3+ debug: 4.4.3([email protected])+ diff: 8.0.3+ empathic: 2.0.0+ hookable: 5.5.3+ rolldown: 1.0.0-beta.60+ rolldown-plugin-dts: 0.13.14([email protected])([email protected])+ semver: 7.7.3+ tinyexec: 1.0.2+ tinyglobby: 0.2.15+ unconfig: 7.4.2+ optionalDependencies:+ typescript: 5.9.3+ transitivePeerDependencies:+ - '@typescript/native-preview'+ - oxc-resolver+ - supports-color+ - vue-tsc+@@ -6212,6 +6430,19 @@ snapshots:+ dependencies:+ '@quansync/fs': 1.0.0+ quansync: 1.0.0++ dependencies:+ '@quansync/fs': 1.0.0+ defu: 6.1.4+ jiti: 2.6.1+ quansync: 1.0.0+ unconfig-core: 7.4.2+dependencies:acorn: 8.15.0@@ -6219,6 +6450,8 @@ snapshots:magic-string: 0.30.21unplugin: 2.3.11+ [email protected]: {}+