@stacksjs/logging 0.70.45 → 0.70.53
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/LICENSE.md +21 -0
- package/dist/index.d.ts +93 -12
- package/dist/index.js +7 -4
- package/package.json +7 -7
package/LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Open Web Foundation
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,32 @@
|
|
|
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;
|
|
1
30
|
/**
|
|
2
31
|
* Run a function with an attached log context (e.g., request ID).
|
|
3
32
|
* Use in HTTP middleware to propagate context through the request lifecycle.
|
|
@@ -12,35 +41,87 @@ declare function getLogger(): Promise<Logger>;
|
|
|
12
41
|
export declare function dump(...args: any[]): Promise<void>;
|
|
13
42
|
export declare function dd(...args: any[]): Promise<never>;
|
|
14
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;
|
|
15
62
|
export declare const log: Log;
|
|
16
63
|
export declare const struct: unknown;
|
|
17
64
|
// Request context propagation for structured logging
|
|
18
|
-
declare interface LogContext {
|
|
65
|
+
export declare interface LogContext {
|
|
19
66
|
requestId?: string
|
|
20
67
|
userId?: string | number
|
|
21
68
|
[key: string]: unknown
|
|
22
69
|
}
|
|
70
|
+
export declare interface ResolvedLogSettings {
|
|
71
|
+
level: LogLevel
|
|
72
|
+
format: LogFormat
|
|
73
|
+
writeToFile: boolean
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Normalize any thrown value into a stable, serializable shape
|
|
77
|
+
* (stacksjs/stacks#1932). `JSON.stringify(new Error())` yields `{}`,
|
|
78
|
+
* dropping the stack/message — so historically `log.error('x', err)`
|
|
79
|
+
* lost the error entirely. This walks `.cause` (bounded) and always
|
|
80
|
+
* captures name/message/stack.
|
|
81
|
+
*/
|
|
82
|
+
export declare interface NormalizedError {
|
|
83
|
+
name: string
|
|
84
|
+
message: string
|
|
85
|
+
stack?: string
|
|
86
|
+
cause?: NormalizedError
|
|
87
|
+
}
|
|
23
88
|
export declare interface Log {
|
|
24
|
-
info: (...args:
|
|
89
|
+
info: (...args: unknown[]) => Promise<void>
|
|
25
90
|
success: (msg: string) => Promise<void>
|
|
26
|
-
error: (
|
|
27
|
-
warn: (arg: string,
|
|
91
|
+
error: (message: string | Error | unknown, error?: unknown, context?: LogContext) => Promise<void>
|
|
92
|
+
warn: (arg: string, context?: LogContext) => Promise<void>
|
|
28
93
|
warning: (arg: string) => Promise<void>
|
|
29
|
-
debug: (...args:
|
|
30
|
-
dump: (...args:
|
|
31
|
-
dd: (...args:
|
|
32
|
-
echo: (...args:
|
|
33
|
-
time: (label: string) => (metadata?:
|
|
94
|
+
debug: (...args: unknown[]) => Promise<void>
|
|
95
|
+
dump: (...args: unknown[]) => Promise<void>
|
|
96
|
+
dd: (...args: unknown[]) => Promise<void>
|
|
97
|
+
echo: (...args: unknown[]) => Promise<void>
|
|
98
|
+
time: (label: string) => (metadata?: LogContext) => Promise<void>
|
|
34
99
|
syncWarn: (msg: string) => void
|
|
35
100
|
syncError: (msg: string) => void
|
|
36
101
|
fatal: (msg: string, exitCode?: number) => never
|
|
37
102
|
flush: () => Promise<void>
|
|
38
103
|
}
|
|
39
|
-
|
|
40
|
-
|
|
104
|
+
/**
|
|
105
|
+
* @deprecated stacksjs/stacks#1932 — the old union form
|
|
106
|
+
* (`{…} | any | Error`) included `| any`, which collapsed the whole
|
|
107
|
+
* union and let `log.error(msg, anything)` type-check while silently
|
|
108
|
+
* dropping the error. Prefer `log.error(message, error?, context?)`.
|
|
109
|
+
* This explicit object shape is retained only for the legacy
|
|
110
|
+
* `{ shouldExit }` fatal path.
|
|
111
|
+
*/
|
|
112
|
+
export declare interface LogErrorOptions {
|
|
41
113
|
shouldExit: boolean
|
|
42
114
|
silent?: boolean
|
|
43
115
|
message?: ErrorMessage
|
|
44
|
-
}
|
|
116
|
+
}
|
|
117
|
+
export declare interface ReportOptions {
|
|
118
|
+
status?: number
|
|
119
|
+
context?: LogContext
|
|
120
|
+
label?: string
|
|
121
|
+
}
|
|
122
|
+
/** Valid log levels — mirrors `@stacksjs/clarity`'s `LogLevel`. */
|
|
123
|
+
export type LogLevel = 'debug' | 'info' | 'success' | 'warning' | 'error';
|
|
124
|
+
export type LogFormat = 'json' | 'text';
|
|
125
|
+
export type ErrorMessage = string;
|
|
45
126
|
// Export logger getter for debugging
|
|
46
127
|
export { getLogger as logger };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
3
|
-
`)}
|
|
4
|
-
`)}
|
|
5
|
-
`
|
|
2
|
+
var A=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 I}from"@stacksjs/types";var W=null,T=null,j=new Set;function O(B){return j.add(B),B.finally(()=>j.delete(B)).catch(()=>{}),B}var M=!1;function E(){if(M)return;M=!0,X.on("beforeExit",()=>{G.flush()})}var b=new Set(["debug","info","success","warning","error"]);function z(B,H="info"){if(!B)return H;let J=B.toLowerCase();if(J==="warn")return"warning";if(b.has(J))return J;return X.stderr.write(`[logging] Ignoring invalid LOG_LEVEL="${B}" (expected: ${[...b].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?z(B.envLevel):B.cfgLevel?z(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(R(B))}}catch{return{name:"Error",message:String(B)}}}function S(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 R(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)=>R(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]=R(Z,H+1);return Q}function D(B){return R(B)}var F=new w;function o(B,H){return F.run(B,H)}function _(){return F.getStore()}async function x(){if(W)return;if(T)return T;return E(),T=(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:V}=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:V})})(),T}async function $(){return await x(),W}function Y(...B){let H=B.map((Q)=>{if(Q instanceof Error)return S(q(Q));if(typeof Q==="object"&&Q!==null)return JSON.stringify(R(Q),null,2);return String(Q)}).join(" "),J=F.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)=>{await(await $()).warn(B,H?D(H):void 0)},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=S(q(B));if(H!==void 0&&!Q)U=`${U} ${S(q(H))}`;let Z={..._(),...J};if(Object.keys(Z).length>0)try{U=`${U} ${JSON.stringify(D(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(I.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(D(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=I.FatalError)=>{X.stderr.write(`${B}
|
|
8
|
+
`),X.exit(H)},flush:async()=>{if(j.size>0)await Promise.allSettled([...j]);if(!W&&!T)return;try{let B=await $(),H=B.flush;if(typeof H==="function")await H.call(B)}catch{}}};async function a(...B){for(let H of B)await G.debug(H)}async function s(...B){let H=Y(...B);console.log(H),X.exit(I.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 N(B,H,J){let Q=_(),U={event:H,traceId:Q?.requestId,...J};if(B==="warn")O(G.warn(`[${H}]`,U));else O(G[B](U))}var c={request(B,H,J,Q,U={}){let Z=J>=500?"error":J>=400?"warn":"info";N(Z,"http.request",{method:B,path:H,status:J,durationMs:Q,...U})},query(B,H,J={}){N("debug","db.query",{sql:B,durationMs:H,...J})},slowQuery(B,H,J={}){N("warn","db.slow_query",{sql:B,durationMs:H,...J})},job(B,H,J={}){N(H==="failed"?"error":"info",`job.${H}`,{jobName:B,...J})},cache(B,H,J={}){N("debug",`cache.${B}`,{key:H,...J})}};G.struct=c;export{o as withLogContext,c as struct,L as resolveLogSettings,r as report,S as renderNormalizedError,z as parseLogLevel,h as parseLogFormat,q as normalizeError,D as normalizeContext,$ as logger,G as log,_ as getLogContext,t as echo,a as dump,s as dd};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stacksjs/logging",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.70.
|
|
4
|
+
"version": "0.70.53",
|
|
5
5
|
"description": "The Stacks logging system.",
|
|
6
6
|
"author": "Chris Breuer",
|
|
7
7
|
"contributors": [
|
|
@@ -49,12 +49,12 @@
|
|
|
49
49
|
},
|
|
50
50
|
"devDependencies": {
|
|
51
51
|
"@stacksjs/clarity": "^0.3.24",
|
|
52
|
-
"@stacksjs/cli": "
|
|
53
|
-
"@stacksjs/config": "
|
|
54
|
-
"@stacksjs/error-handling": "
|
|
55
|
-
"@stacksjs/path": "
|
|
56
|
-
"@stacksjs/storage": "
|
|
57
|
-
"@stacksjs/validation": "
|
|
52
|
+
"@stacksjs/cli": "0.70.53",
|
|
53
|
+
"@stacksjs/config": "0.70.53",
|
|
54
|
+
"@stacksjs/error-handling": "0.70.53",
|
|
55
|
+
"@stacksjs/path": "0.70.53",
|
|
56
|
+
"@stacksjs/storage": "0.70.53",
|
|
57
|
+
"@stacksjs/validation": "0.70.53",
|
|
58
58
|
"typescript": "^6.0.2"
|
|
59
59
|
}
|
|
60
60
|
}
|