@stacksjs/logging 0.70.87 → 0.70.88

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/logging",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.70.87",
5
+ "version": "0.70.88",
6
6
  "description": "The Stacks logging system.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -54,12 +54,12 @@
54
54
  },
55
55
  "devDependencies": {
56
56
  "@stacksjs/clarity": "^0.3.24",
57
- "@stacksjs/cli": "0.70.87",
58
- "@stacksjs/config": "0.70.87",
59
- "@stacksjs/error-handling": "0.70.87",
60
- "@stacksjs/path": "0.70.87",
61
- "@stacksjs/storage": "0.70.87",
62
- "@stacksjs/validation": "0.70.87",
57
+ "@stacksjs/cli": "0.70.88",
58
+ "@stacksjs/config": "0.70.88",
59
+ "@stacksjs/error-handling": "0.70.88",
60
+ "@stacksjs/path": "0.70.88",
61
+ "@stacksjs/storage": "0.70.88",
62
+ "@stacksjs/validation": "0.70.88",
63
63
  "typescript": "^7.0.2"
64
64
  }
65
65
  }
package/dist/index.d.ts DELETED
@@ -1,148 +0,0 @@
1
- /**
2
- * Parse + validate `LOG_LEVEL` (stacksjs/stacks#1932). Previously the
3
- * env value was cast `as any` straight into the logger, so a typo
4
- * (`LOG_LEVEL=infoo`) silently produced undefined behavior. Now an
5
- * unknown value warns once and falls back. Accepts `warn` as an alias
6
- * for clarity's `warning`.
7
- */
8
- export declare function parseLogLevel(raw: string | undefined, fallback?: LogLevel): LogLevel;
9
- /** Parse + validate `LOG_FORMAT`; defaults to json in prod, text in dev. */
10
- export declare function parseLogFormat(raw: string | undefined): LogFormat;
11
- /**
12
- * Resolve the effective logger settings with precedence
13
- * **env var > config file > default** (stacksjs/stacks#1935). Pure +
14
- * exported so the precedence is unit-testable without booting the
15
- * singleton logger.
16
- */
17
- export declare function resolveLogSettings(input: {
18
- envLevel?: string
19
- envFormat?: string
20
- cfgLevel?: string
21
- cfgFormat?: string
22
- cfgWriteToFile?: boolean
23
- isProduction?: boolean
24
- }): ResolvedLogSettings;
25
- export declare function normalizeError(err: unknown, depth?: number): NormalizedError;
26
- /** Render a normalized error (+ its cause chain) to a printable string. */
27
- export declare function renderNormalizedError(n: NormalizedError): string;
28
- /** Apply {@link normalizeContextValue} to a structured log context. */
29
- export declare function normalizeContext(ctx: LogContext): LogContext;
30
- /**
31
- * Run a function with an attached log context (e.g., request ID).
32
- * Use in HTTP middleware to propagate context through the request lifecycle.
33
- */
34
- export declare function withLogContext<T>(context: LogContext, fn: () => T): T;
35
- /**
36
- * Get the current log context (if any).
37
- */
38
- export declare function getLogContext(): LogContext | undefined;
39
- declare function getLogger(): Promise<Logger>;
40
- // Export convenience functions
41
- export declare function dump(...args: any[]): Promise<void>;
42
- export declare function dd(...args: any[]): Promise<never>;
43
- export declare function echo(...args: any[]): Promise<void>;
44
- /**
45
- * Single error→log chokepoint (stacksjs/stacks#1933) — Laravel's
46
- * `report()`. Every automatic error-logging path (router action catch,
47
- * request catch, process-level handlers) funnels through here so the
48
- * policy lives in one place:
49
- *
50
- * - **4xx** (client errors — a thrown `HttpError(404)` / `422`) are
51
- * NOT reported at error level; they're expected control flow, not
52
- * server faults. Logged at debug so they stay traceable without
53
- * spamming the error stream.
54
- * - **5xx** and any non-HTTP throw are always reported at `error`
55
- * with the full normalized stack + cause chain + request context.
56
- *
57
- * Fire-and-forget by design (callers are on a response / exit path);
58
- * the write is queued through the shared logger so a flush-on-exit
59
- * (stacksjs/stacks#1934) drains it.
60
- */
61
- export declare function report(error: unknown, options?: ReportOptions): void;
62
- declare function emit(level: 'debug' | 'info' | 'warn' | 'error', event: string, fields: StructuredFields): void;
63
- export declare const log: Log;
64
- export declare const struct: unknown;
65
- // Request context propagation for structured logging
66
- export declare interface LogContext {
67
- requestId?: string
68
- userId?: string | number
69
- [key: string]: unknown
70
- }
71
- export declare interface ResolvedLogSettings {
72
- level: LogLevel
73
- format: LogFormat
74
- writeToFile: boolean
75
- }
76
- /**
77
- * Normalize any thrown value into a stable, serializable shape
78
- * (stacksjs/stacks#1932). `JSON.stringify(new Error())` yields `{}`,
79
- * dropping the stack/message — so historically `log.error('x', err)`
80
- * lost the error entirely. This walks `.cause` (bounded) and always
81
- * captures name/message/stack.
82
- */
83
- export declare interface NormalizedError {
84
- name: string
85
- message: string
86
- stack?: string
87
- cause?: NormalizedError
88
- }
89
- export declare interface Log {
90
- info: (...args: unknown[]) => Promise<void>
91
- success: (msg: string) => Promise<void>
92
- error: (message: string | Error | unknown, error?: unknown, context?: LogContext) => Promise<void>
93
- warn: (arg: string, context?: unknown) => Promise<void>
94
- warning: (arg: string) => Promise<void>
95
- debug: (...args: unknown[]) => Promise<void>
96
- dump: (...args: unknown[]) => Promise<void>
97
- dd: (...args: unknown[]) => Promise<void>
98
- echo: (...args: unknown[]) => Promise<void>
99
- time: (label: string) => (metadata?: LogContext) => Promise<void>
100
- syncWarn: (msg: string) => void
101
- syncError: (msg: string) => void
102
- fatal: (msg: string, exitCode?: number) => never
103
- flush: () => Promise<void>
104
- }
105
- /**
106
- * @deprecated stacksjs/stacks#1932 — the old union form
107
- * (`{…} | any | Error`) included `| any`, which collapsed the whole
108
- * union and let `log.error(msg, anything)` type-check while silently
109
- * dropping the error. Prefer `log.error(message, error?, context?)`.
110
- * This explicit object shape is retained only for the legacy
111
- * `{ shouldExit }` fatal path.
112
- */
113
- export declare interface LogErrorOptions {
114
- shouldExit: boolean
115
- silent?: boolean
116
- message?: ErrorMessage
117
- }
118
- export declare interface ReportOptions {
119
- status?: number
120
- context?: LogContext
121
- label?: string
122
- }
123
- /**
124
- * Structured logging shorthands for common framework events.
125
- *
126
- * The bare `log.info("…")` form is good for ad-hoc messages, but the
127
- * framework emits a predictable set of events (HTTP requests, DB
128
- * queries, queued jobs, cache operations) that benefit from a stable
129
- * shape so downstream log shippers can index on consistent field
130
- * names.
131
- *
132
- * Each helper:
133
- * 1. Attaches the current trace id (if any) automatically
134
- * 2. Picks the appropriate severity based on outcome
135
- * 3. Emits a consistent JSON shape in production (`event`, `level`,
136
- * `traceId`, …) while keeping the human-readable form in dev
137
- *
138
- * Helpers are batched onto `log.struct` so they don't pollute the
139
- * top-level `log` namespace, and so users can opt out by routing
140
- * `log.struct` to a custom transport in tests.
141
- */
142
- declare interface StructuredFields { [key: string]: unknown }
143
- /** Valid log levels — mirrors `@stacksjs/clarity`'s `LogLevel`. */
144
- export type LogLevel = 'debug' | 'info' | 'success' | 'warning' | 'error';
145
- export type LogFormat = 'json' | 'text';
146
- export type ErrorMessage = string;
147
- // Export logger getter for debugging
148
- export { getLogger as logger };
package/dist/index.js DELETED
@@ -1,8 +0,0 @@
1
- // @bun
2
- var N=import.meta.require;import{AsyncLocalStorage as w}from"async_hooks";import X from"process";import{Logger as k}from"@stacksjs/clarity";import{handleError as C}from"@stacksjs/error-handling";import{ExitCode as D}from"@stacksjs/types";var W=null,R=null,j=new Set;function V(B){return j.add(B),B.finally(()=>j.delete(B)).catch(()=>{}),B}var O=!1;function E(){if(O)return;O=!0,X.on("beforeExit",()=>{G.flush()})}var M=new Set(["debug","info","success","warning","error"]);function b(B,H="info"){if(!B)return H;let J=B.toLowerCase();if(J==="warn")return"warning";if(M.has(J))return J;return X.stderr.write(`[logging] Ignoring invalid LOG_LEVEL="${B}" (expected: ${[...M].join(", ")}); using "${H}".
3
- `),H}function h(B){if(B==="json"||B==="text")return B;if(B)X.stderr.write(`[logging] Ignoring invalid LOG_FORMAT="${B}" (expected "json" or "text").
4
- `);return X.env.NODE_ENV==="production"?"json":"text"}function L(B){let H=B.envLevel?b(B.envLevel):B.cfgLevel?b(B.cfgLevel):"info",J=B.envFormat?h(B.envFormat):B.cfgFormat==="json"||B.cfgFormat==="text"?B.cfgFormat:B.isProduction?"json":"text";return{level:H,format:J,writeToFile:B.cfgWriteToFile??!0}}function q(B,H=0){if(H>8)return{name:"Error",message:"[cause chain truncated]"};if(B instanceof Error)return{name:B.name,message:B.message,stack:B.stack,cause:B.cause!=null?q(B.cause,H+1):void 0};if(typeof B==="string")return{name:"Error",message:B};if(B==null)return{name:"Error",message:String(B)};try{return{name:"Error",message:JSON.stringify(A(B))}}catch{return{name:"Error",message:String(B)}}}function I(B){let H=B.stack||`${B.name}: ${B.message}`,J=B.cause;while(J)H+=`
5
- caused by: ${J.stack||`${J.name}: ${J.message}`}`,J=J.cause;return H}function A(B,H=0){if(B instanceof Error)return q(B);if(H>=4||B===null||typeof B!=="object")return B;if(Array.isArray(B))return B.map((U)=>A(U,H+1));let J=Object.getPrototypeOf(B);if(J!==Object.prototype&&J!==null)return B;let Q={};for(let[U,Z]of Object.entries(B))Q[U]=A(Z,H+1);return Q}function _(B){return A(B)}var S=new w;function o(B,H){return S.run(B,H)}function y(){return S.getStore()}async function x(){if(W)return;if(R)return R;return E(),R=(async()=>{let B,H,J,Q;try{let K=(await import("@stacksjs/config")).logging;if(K){if(B=K.level,H=K.format,typeof K.writeToFile==="boolean")Q=K.writeToFile;if(K.logsPath)J=(await import("path")).dirname(K.logsPath)}}catch{}let{level:U,format:Z,writeToFile:F}=L({envLevel:X.env.LOG_LEVEL,envFormat:X.env.LOG_FORMAT,cfgLevel:B,cfgFormat:H,cfgWriteToFile:Q,isProduction:X.env.NODE_ENV==="production"}),P=J;if(!P)try{P=(await import("@stacksjs/path")).projectPath("storage/logs")}catch{P="storage/logs"}W=new k("stacks",{level:U,logDirectory:P,showTags:!1,fancy:Z!=="json",format:Z,writeToFile:F})})(),R}async function $(){return await x(),W}function Y(...B){let H=B.map((Q)=>{if(Q instanceof Error)return I(q(Q));if(typeof Q==="object"&&Q!==null)return JSON.stringify(A(Q),null,2);return String(Q)}).join(" "),J=S.getStore();if(J?.requestId)return`[${J.requestId}] ${H}`;return H}var f=new Set(["shouldExit","silent","message"]);function v(B){if(!B||typeof B!=="object"||B instanceof Error)return!1;if(!(("shouldExit"in B)||("silent"in B)))return!1;return Object.keys(B).every((H)=>f.has(H))}var G={info:async(...B)=>{let H=Y(...B);await(await $()).info(H)},success:async(B)=>{await(await $()).success(B)},warn:async(B,H)=>{let J=await $(),Q=H===void 0?void 0:A(H);await J.warn(B,Q)},warning:async(B)=>{await(await $()).warn(B)},error:async(B,H,J)=>{let Q=v(H)?H:void 0,U;if(typeof B==="string")U=B;else U=I(q(B));if(H!==void 0&&!Q)U=`${U} ${I(q(H))}`;let Z={...y(),...J};if(Object.keys(Z).length>0)try{U=`${U} ${JSON.stringify(_(Z))}`}catch{}if(await(await $()).error(U),Q?.shouldExit)C(B,Q)},debug:async(...B)=>{let H=(X.env.LOG_LEVEL||"info").toLowerCase();if(H==="info"||H==="warn"||H==="error")return;let J=Y(...B);await(await $()).debug(J)},dump:async(...B)=>{let H=Y(...B);await(await $()).debug(`DUMP: ${H}`)},dd:async(...B)=>{let H=Y(...B);await(await $()).error(H),X.exit(D.FatalError)},echo:async(...B)=>{let H=Y(...B);await(await $()).info(`ECHO: ${H}`)},time:(B)=>{let H=performance.now();return async(J)=>{let Q=performance.now()-H,U=await $(),Z=J?` ${JSON.stringify(_(J))}`:"";await U.info(`${B}: ${Q.toFixed(2)}ms${Z}`)}},syncWarn:(B)=>{X.stderr.write(`${B}
6
- `)},syncError:(B)=>{X.stderr.write(`${B}
7
- `)},fatal:(B,H=D.FatalError)=>{X.stderr.write(`${B}
8
- `),X.exit(H)},flush:async()=>{if(j.size>0)await Promise.allSettled([...j]);if(!W&&!R)return;try{let B=await $(),H=B.flush;if(typeof H==="function")await H.call(B)}catch{}}};async function s(...B){for(let H of B)await G.debug(H)}async function a(...B){let H=Y(...B);console.log(H),X.exit(D.FatalError)}async function t(...B){await G.debug(...B)}function d(B){if(B&&typeof B==="object"){let H=B;if(typeof H.status==="number")return H.status;if(typeof H.statusCode==="number")return H.statusCode}return}function r(B,H={}){let J=H.status??d(B),Q=typeof J==="number"&&J>=400&&J<500,U=H.label??"Unhandled error",Z={...H.context,...J!=null?{status:J}:{}};if(Q){G.debug(`${U} (client error ${J}): ${q(B).message}`);return}G.error(U,B,Z)}function T(B,H,J){let Q=y(),U={event:H,traceId:Q?.requestId,...J};if(B==="warn")V(G.warn(`[${H}]`,U));else V(G[B](U))}var c={request(B,H,J,Q,U={}){let Z=J>=500?"error":J>=400?"warn":"info";T(Z,"http.request",{method:B,path:H,status:J,durationMs:Q,...U})},query(B,H,J={}){T("debug","db.query",{sql:B,durationMs:H,...J})},slowQuery(B,H,J={}){T("warn","db.slow_query",{sql:B,durationMs:H,...J})},job(B,H,J={}){T(H==="failed"?"error":"info",`job.${H}`,{jobName:B,...J})},cache(B,H,J={}){T("debug",`cache.${B}`,{key:H,...J})}};G.struct=c;export{o as withLogContext,c as struct,L as resolveLogSettings,r as report,I as renderNormalizedError,b as parseLogLevel,h as parseLogFormat,q as normalizeError,_ as normalizeContext,$ as logger,G as log,y as getLogContext,t as echo,s as dump,a as dd};