@lssm/lib.logger 1.7.3 → 1.9.0
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/README.md +26 -525
- package/dist/{context.d.ts → context.d.mts} +2 -2
- package/dist/{context.d.cts.map → context.d.mts.map} +1 -1
- package/dist/{context.js → context.mjs} +1 -1
- package/dist/context.mjs.map +1 -0
- package/dist/{elysia-plugin.d.cts → elysia-plugin.d.mts} +3 -3
- package/dist/{elysia-plugin.d.cts.map → elysia-plugin.d.mts.map} +1 -1
- package/dist/elysia-plugin.mjs +2 -0
- package/dist/elysia-plugin.mjs.map +1 -0
- package/dist/{formatters.d.cts → formatters.d.mts} +2 -2
- package/dist/{formatters.d.cts.map → formatters.d.mts.map} +1 -1
- package/dist/{formatters.js → formatters.mjs} +2 -2
- package/dist/formatters.mjs.map +1 -0
- package/dist/{index.d.cts → index.d.mts} +7 -7
- package/dist/index.mjs +1 -0
- package/dist/{logger.d.cts → logger.d.mts} +3 -3
- package/dist/{logger.d.cts.map → logger.d.mts.map} +1 -1
- package/dist/logger.mjs +2 -0
- package/dist/logger.mjs.map +1 -0
- package/dist/{timer.d.ts → timer.d.mts} +2 -2
- package/dist/{timer.d.cts.map → timer.d.mts.map} +1 -1
- package/dist/{timer.js → timer.mjs} +1 -1
- package/dist/timer.mjs.map +1 -0
- package/dist/{tracer.d.cts → tracer.d.mts} +2 -2
- package/dist/{tracer.d.cts.map → tracer.d.mts.map} +1 -1
- package/dist/tracer.mjs +2 -0
- package/dist/tracer.mjs.map +1 -0
- package/dist/{types.d.cts → types.d.mts} +1 -1
- package/dist/{types.d.cts.map → types.d.mts.map} +1 -1
- package/dist/{types.js → types.mjs} +1 -1
- package/dist/types.mjs.map +1 -0
- package/package.json +15 -39
- package/dist/_virtual/rolldown_runtime.cjs +0 -1
- package/dist/context.cjs +0 -1
- package/dist/context.d.cts +0 -44
- package/dist/context.d.ts.map +0 -1
- package/dist/context.js.map +0 -1
- package/dist/elysia-plugin.cjs +0 -1
- package/dist/elysia-plugin.d.ts +0 -64
- package/dist/elysia-plugin.d.ts.map +0 -1
- package/dist/elysia-plugin.js +0 -2
- package/dist/elysia-plugin.js.map +0 -1
- package/dist/formatters.cjs +0 -9
- package/dist/formatters.d.ts +0 -29
- package/dist/formatters.d.ts.map +0 -1
- package/dist/formatters.js.map +0 -1
- package/dist/index.cjs +0 -1
- package/dist/index.d.ts +0 -8
- package/dist/index.js +0 -1
- package/dist/logger.cjs +0 -1
- package/dist/logger.d.ts +0 -51
- package/dist/logger.d.ts.map +0 -1
- package/dist/logger.js +0 -2
- package/dist/logger.js.map +0 -1
- package/dist/timer.cjs +0 -1
- package/dist/timer.d.cts +0 -103
- package/dist/timer.d.ts.map +0 -1
- package/dist/timer.js.map +0 -1
- package/dist/tracer.cjs +0 -1
- package/dist/tracer.d.ts +0 -51
- package/dist/tracer.d.ts.map +0 -1
- package/dist/tracer.js +0 -2
- package/dist/tracer.js.map +0 -1
- package/dist/types.cjs +0 -1
- package/dist/types.d.ts +0 -71
- package/dist/types.d.ts.map +0 -1
- package/dist/types.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LogLevel as e}from"./types.
|
|
1
|
+
import{LogLevel as e}from"./types.mjs";const t={reset:`\x1B[0m`,bright:`\x1B[1m`,dim:`\x1B[2m`,red:`\x1B[31m`,green:`\x1B[32m`,yellow:`\x1B[33m`,blue:`\x1B[34m`,magenta:`\x1B[35m`,cyan:`\x1B[36m`,white:`\x1B[37m`,gray:`\x1B[90m`,bgRed:`\x1B[41m`,bgYellow:`\x1B[43m`},n={[e.TRACE]:{color:t.gray,symbol:`○`,name:`TRACE`},[e.DEBUG]:{color:t.blue,symbol:`●`,name:`DEBUG`},[e.INFO]:{color:t.green,symbol:`●`,name:`INFO `},[e.WARN]:{color:t.yellow,symbol:`▲`,name:`WARN `},[e.ERROR]:{color:t.red,symbol:`✖`,name:`ERROR`},[e.FATAL]:{color:t.bgRed+t.white,symbol:`💀`,name:`FATAL`}};var r=class{enableColors;constructor(e=!0){this.enableColors=e}format(e){let r=[],i=n[e.level],a=this.formatTimestamp(e.timestamp);r.push(this.colorize(a,t.gray));let o=`${i.symbol} ${i.name}`;if(r.push(this.colorize(o,i.color)),e.traceId){let n=this.formatTraceInfo(e);r.push(this.colorize(n,t.cyan))}if(r.push(this.colorize(e.message,t.white)),e.duration!==void 0){let n=`(${this.formatDuration(e.duration)})`;r.push(this.colorize(n,t.magenta))}let s=r.join(` `);if(e.context&&Object.keys(e.context).length>0&&(s+=`
|
|
2
2
|
`+this.formatContext(e.context)),e.metadata&&Object.keys(e.metadata).length>0&&(s+=`
|
|
3
3
|
`+this.formatMetadata(e.metadata)),e.error&&(s+=`
|
|
4
4
|
`+this.formatError(e.error)),e.tags&&e.tags.length>0){let n=e.tags.map(e=>`#${e}`).join(` `);s+=`
|
|
@@ -7,4 +7,4 @@ import{LogLevel as e}from"./types.js";const t={reset:`\x1B[0m`,bright:`\x1B[1m`,
|
|
|
7
7
|
`);n+=`
|
|
8
8
|
`+this.colorize(r,t.gray)}return n}formatObject(e,t=0){let n=` `.repeat(t),r=Object.entries(e);return r.length===0?`{}`:r[0]&&typeof r[0][1]!=`object`?`{ ${r[0][0]}: ${this.formatValue(r[0][1])} }`:`{\n${r.map(([e,r])=>`${n} ${e}: ${this.formatValue(r,t+2)}`).join(`
|
|
9
9
|
`)}\n${n}}`}formatValue(e,t=0){return e===null?`null`:e===void 0?`undefined`:typeof e==`string`?`"${e}"`:typeof e==`boolean`||typeof e==`number`?String(e):e instanceof Date?e.toISOString():Array.isArray(e)?e.length===0?`[]`:`[${e.map(e=>this.formatValue(e)).join(`, `)}]`:typeof e==`object`?this.formatObject(e,t):String(e)}colorize(e,n){return this.enableColors?`${n}${e}${t.reset}`:e}},i=class{format(e){let t={timestamp:e.timestamp,level:e.level,message:e.message};return e.traceId&&(t.traceId=e.traceId),e.spanId&&(t.spanId=e.spanId),e.parentId&&(t.parentId=e.parentId),e.duration!==void 0&&(t.duration=e.duration),e.context&&Object.keys(e.context).length>0&&(t.context=e.context),e.metadata&&Object.keys(e.metadata).length>0&&(t.metadata=e.metadata),e.error&&(t.error={name:e.error.name,message:e.error.message,stack:e.error.stack}),e.tags&&e.tags.length>0&&(t.tags=e.tags),JSON.stringify(t)}},a=class{template;dateFormat;constructor(e=`{timestamp} [{level}] {message}`,t){this.template=e,this.dateFormat=t||(e=>e.toISOString())}format(t){let n=e[t.level],r=this.dateFormat(t.timestamp),i=this.template.replace(`{timestamp}`,r).replace(`{level}`,n).replace(`{message}`,t.message).replace(`{traceId}`,t.traceId||``).replace(`{spanId}`,t.spanId||``).replace(`{duration}`,t.duration?.toString()||``);return t.context&&(i=i.replace(`{context}`,JSON.stringify(t.context))),t.metadata&&(i=i.replace(`{metadata}`,JSON.stringify(t.metadata))),i}};export{a as CustomFormatter,r as DevFormatter,i as ProductionFormatter};
|
|
10
|
-
//# sourceMappingURL=formatters.
|
|
10
|
+
//# sourceMappingURL=formatters.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"formatters.mjs","names":["parts: string[]","logObject: LogEntry"],"sources":["../src/formatters.ts"],"sourcesContent":["import type { Formatter, LogEntry } from './types';\nimport { LogLevel } from './types';\n\n// ANSI color codes for terminal output\nconst colors = {\n reset: '\\x1b[0m',\n bright: '\\x1b[1m',\n dim: '\\x1b[2m',\n red: '\\x1b[31m',\n green: '\\x1b[32m',\n yellow: '\\x1b[33m',\n blue: '\\x1b[34m',\n magenta: '\\x1b[35m',\n cyan: '\\x1b[36m',\n white: '\\x1b[37m',\n gray: '\\x1b[90m',\n bgRed: '\\x1b[41m',\n bgYellow: '\\x1b[43m',\n};\n\n// Log level colors and symbols\nconst levelConfig = {\n [LogLevel.TRACE]: { color: colors.gray, symbol: '○', name: 'TRACE' },\n [LogLevel.DEBUG]: { color: colors.blue, symbol: '●', name: 'DEBUG' },\n [LogLevel.INFO]: { color: colors.green, symbol: '●', name: 'INFO ' },\n [LogLevel.WARN]: { color: colors.yellow, symbol: '▲', name: 'WARN ' },\n [LogLevel.ERROR]: { color: colors.red, symbol: '✖', name: 'ERROR' },\n [LogLevel.FATAL]: {\n color: colors.bgRed + colors.white,\n symbol: '💀',\n name: 'FATAL',\n },\n};\n\nexport class DevFormatter implements Formatter {\n private enableColors: boolean;\n\n constructor(enableColors = true) {\n this.enableColors = enableColors;\n }\n\n format(entry: LogEntry): string {\n const parts: string[] = [];\n const config = levelConfig[entry.level];\n\n // Timestamp\n const timestamp = this.formatTimestamp(entry.timestamp);\n parts.push(this.colorize(timestamp, colors.gray));\n\n // Log level with symbol\n const levelText = `${config.symbol} ${config.name}`;\n parts.push(this.colorize(levelText, config.color));\n\n // Trace information\n if (entry.traceId) {\n const traceInfo = this.formatTraceInfo(entry);\n parts.push(this.colorize(traceInfo, colors.cyan));\n }\n\n // Main message\n parts.push(this.colorize(entry.message, colors.white));\n\n // Duration (if present)\n if (entry.duration !== undefined) {\n const durationText = `(${this.formatDuration(entry.duration)})`;\n parts.push(this.colorize(durationText, colors.magenta));\n }\n\n let output = parts.join(' ');\n\n // Context and metadata (on new lines for readability)\n if (entry.context && Object.keys(entry.context).length > 0) {\n output += '\\n' + this.formatContext(entry.context);\n }\n\n if (entry.metadata && Object.keys(entry.metadata).length > 0) {\n output += '\\n' + this.formatMetadata(entry.metadata);\n }\n\n // Error details\n if (entry.error) {\n output += '\\n' + this.formatError(entry.error);\n }\n\n // Tags\n if (entry.tags && entry.tags.length > 0) {\n const tagsText = entry.tags.map((tag) => `#${tag}`).join(' ');\n output += '\\n' + this.colorize(`Tags: ${tagsText}`, colors.blue);\n }\n\n return output;\n }\n\n private formatTimestamp(timestamp: Date): string {\n return timestamp.toISOString().substring(11, 23); // Just time with milliseconds\n }\n\n private formatTraceInfo(entry: LogEntry): string {\n const parts = [`trace:${entry.traceId?.substring(0, 8) || 'unknown'}`];\n if (entry.spanId && entry.spanId.length >= 8) {\n parts.push(`span:${entry.spanId.substring(0, 8)}`);\n }\n if (entry.parentId && entry.parentId.length >= 8) {\n parts.push(`parent:${entry.parentId.substring(0, 8)}`);\n }\n return `[${parts.join('|')}]`;\n }\n\n private formatDuration(duration: number): string {\n if (duration < 1) {\n return `${(duration * 1000).toFixed(0)}μs`;\n } else if (duration < 1000) {\n return `${duration.toFixed(2)}ms`;\n } else {\n return `${(duration / 1000).toFixed(2)}s`;\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private formatContext(context: Record<string, any>): string {\n const formatted = this.formatObject(context, 2);\n return this.colorize(`Context: ${formatted}`, colors.cyan);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private formatMetadata(metadata: Record<string, any>): string {\n const formatted = this.formatObject(metadata, 2);\n return this.colorize(`Metadata: ${formatted}`, colors.blue);\n }\n\n private formatError(error: Error): string {\n let output = this.colorize(\n `Error: ${error.name}: ${error.message}`,\n colors.red\n );\n if (error.stack) {\n const stackLines = error.stack.split('\\n').slice(1, 6); // First 5 stack frames\n const indentedStack = stackLines.map((line) => ` ${line}`).join('\\n');\n output += '\\n' + this.colorize(indentedStack, colors.gray);\n }\n return output;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private formatObject(obj: Record<string, any>, indent = 0): string {\n const spaces = ' '.repeat(indent);\n const entries = Object.entries(obj);\n\n if (entries.length === 0) return '{}';\n\n if (entries[0] && typeof entries[0][1] !== 'object') {\n return `{ ${entries[0][0]}: ${this.formatValue(entries[0][1])} }`;\n }\n\n const formatted = entries\n .map(([key, value]) => {\n return `${spaces} ${key}: ${this.formatValue(value, indent + 2)}`;\n })\n .join('\\n');\n\n return `{\\n${formatted}\\n${spaces}}`;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private formatValue(value: any, indent = 0): string {\n if (value === null) return 'null';\n if (value === undefined) return 'undefined';\n if (typeof value === 'string') return `\"${value}\"`;\n if (typeof value === 'boolean' || typeof value === 'number')\n return String(value);\n if (value instanceof Date) return value.toISOString();\n if (Array.isArray(value)) {\n if (value.length === 0) return '[]';\n return `[${value.map((v) => this.formatValue(v)).join(', ')}]`;\n }\n if (typeof value === 'object') {\n return this.formatObject(value, indent);\n }\n return String(value);\n }\n\n private colorize(text: string, color: string): string {\n if (!this.enableColors) return text;\n return `${color}${text}${colors.reset}`;\n }\n}\n\nexport class ProductionFormatter implements Formatter {\n format(entry: LogEntry): string {\n const logObject: LogEntry = {\n timestamp: entry.timestamp,\n level: entry.level,\n message: entry.message,\n };\n\n // Add trace information\n if (entry.traceId) {\n logObject.traceId = entry.traceId;\n }\n if (entry.spanId) {\n logObject.spanId = entry.spanId;\n }\n if (entry.parentId) {\n logObject.parentId = entry.parentId;\n }\n\n // Add timing information\n if (entry.duration !== undefined) {\n logObject.duration = entry.duration;\n }\n\n // Add context and metadata\n if (entry.context && Object.keys(entry.context).length > 0) {\n logObject.context = entry.context;\n }\n if (entry.metadata && Object.keys(entry.metadata).length > 0) {\n logObject.metadata = entry.metadata;\n }\n\n // Add error information\n if (entry.error) {\n logObject.error = {\n name: entry.error.name,\n message: entry.error.message,\n stack: entry.error.stack,\n };\n }\n\n // Add tags\n if (entry.tags && entry.tags.length > 0) {\n logObject.tags = entry.tags;\n }\n\n return JSON.stringify(logObject);\n }\n}\n\nexport class CustomFormatter implements Formatter {\n private template: string;\n private dateFormat: (date: Date) => string;\n\n constructor(\n template = '{timestamp} [{level}] {message}',\n dateFormat?: (date: Date) => string\n ) {\n this.template = template;\n this.dateFormat = dateFormat || ((date: Date) => date.toISOString());\n }\n\n format(entry: LogEntry): string {\n const levelName = LogLevel[entry.level];\n const timestamp = this.dateFormat(entry.timestamp);\n\n let formatted = this.template\n .replace('{timestamp}', timestamp)\n .replace('{level}', levelName)\n .replace('{message}', entry.message)\n .replace('{traceId}', entry.traceId || '')\n .replace('{spanId}', entry.spanId || '')\n .replace('{duration}', entry.duration?.toString() || '');\n\n // Handle context and metadata placeholders\n if (entry.context) {\n formatted = formatted.replace('{context}', JSON.stringify(entry.context));\n }\n if (entry.metadata) {\n formatted = formatted.replace(\n '{metadata}',\n JSON.stringify(entry.metadata)\n );\n }\n\n return formatted;\n }\n}\n"],"mappings":"uCAIA,MAAM,EAAS,CACb,MAAO,UACP,OAAQ,UACR,IAAK,UACL,IAAK,WACL,MAAO,WACP,OAAQ,WACR,KAAM,WACN,QAAS,WACT,KAAM,WACN,MAAO,WACP,KAAM,WACN,MAAO,WACP,SAAU,WACX,CAGK,EAAc,EACjB,EAAS,OAAQ,CAAE,MAAO,EAAO,KAAM,OAAQ,IAAK,KAAM,QAAS,EACnE,EAAS,OAAQ,CAAE,MAAO,EAAO,KAAM,OAAQ,IAAK,KAAM,QAAS,EACnE,EAAS,MAAO,CAAE,MAAO,EAAO,MAAO,OAAQ,IAAK,KAAM,QAAS,EACnE,EAAS,MAAO,CAAE,MAAO,EAAO,OAAQ,OAAQ,IAAK,KAAM,QAAS,EACpE,EAAS,OAAQ,CAAE,MAAO,EAAO,IAAK,OAAQ,IAAK,KAAM,QAAS,EAClE,EAAS,OAAQ,CAChB,MAAO,EAAO,MAAQ,EAAO,MAC7B,OAAQ,KACR,KAAM,QACP,CACF,CAED,IAAa,EAAb,KAA+C,CAC7C,aAEA,YAAY,EAAe,GAAM,CAC/B,KAAK,aAAe,EAGtB,OAAO,EAAyB,CAC9B,IAAMA,EAAkB,EAAE,CACpB,EAAS,EAAY,EAAM,OAG3B,EAAY,KAAK,gBAAgB,EAAM,UAAU,CACvD,EAAM,KAAK,KAAK,SAAS,EAAW,EAAO,KAAK,CAAC,CAGjD,IAAM,EAAY,GAAG,EAAO,OAAO,GAAG,EAAO,OAI7C,GAHA,EAAM,KAAK,KAAK,SAAS,EAAW,EAAO,MAAM,CAAC,CAG9C,EAAM,QAAS,CACjB,IAAM,EAAY,KAAK,gBAAgB,EAAM,CAC7C,EAAM,KAAK,KAAK,SAAS,EAAW,EAAO,KAAK,CAAC,CAOnD,GAHA,EAAM,KAAK,KAAK,SAAS,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UAAU,EAAI,GAAG,CAa1D,OAVI,EAAM,UACR,EAAY,EAAU,QAAQ,YAAa,KAAK,UAAU,EAAM,QAAQ,CAAC,EAEvE,EAAM,WACR,EAAY,EAAU,QACpB,aACA,KAAK,UAAU,EAAM,SAAS,CAC/B,EAGI"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { LogEntry, LogLevel, TraceContext, TracingOptions } from "./types.
|
|
2
|
-
import { LogContext } from "./context.
|
|
3
|
-
import { Timer } from "./timer.
|
|
4
|
-
import { Logger } from "./logger.
|
|
5
|
-
import { createElysiaLogger, elysiaLogger } from "./elysia-plugin.
|
|
6
|
-
import { DevFormatter, ProductionFormatter } from "./formatters.
|
|
7
|
-
import { Tracer } from "./tracer.
|
|
1
|
+
import { LogEntry, LogLevel, TraceContext, TracingOptions } from "./types.mjs";
|
|
2
|
+
import { LogContext } from "./context.mjs";
|
|
3
|
+
import { Timer } from "./timer.mjs";
|
|
4
|
+
import { Logger } from "./logger.mjs";
|
|
5
|
+
import { createElysiaLogger, elysiaLogger } from "./elysia-plugin.mjs";
|
|
6
|
+
import { DevFormatter, ProductionFormatter } from "./formatters.mjs";
|
|
7
|
+
import { Tracer } from "./tracer.mjs";
|
|
8
8
|
export { DevFormatter, LogContext, type LogEntry, LogLevel, Logger, ProductionFormatter, Timer, type TraceContext, Tracer, type TracingOptions, createElysiaLogger, elysiaLogger };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LogContext as e}from"./context.mjs";import{LogLevel as t}from"./types.mjs";import{Timer as n}from"./timer.mjs";import{Tracer as r}from"./tracer.mjs";import{DevFormatter as i,ProductionFormatter as a}from"./formatters.mjs";import{Logger as o}from"./logger.mjs";import{createElysiaLogger as s,elysiaLogger as c}from"./elysia-plugin.mjs";export{i as DevFormatter,e as LogContext,t as LogLevel,o as Logger,a as ProductionFormatter,n as Timer,r as Tracer,s as createElysiaLogger,c as elysiaLogger};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ContextData, Formatter, LogLevel, LoggerConfig, TraceContext, TraceMethod, TracingOptions } from "./types.
|
|
2
|
-
import { Timer } from "./timer.
|
|
1
|
+
import { ContextData, Formatter, LogLevel, LoggerConfig, TraceContext, TraceMethod, TracingOptions } from "./types.mjs";
|
|
2
|
+
import { Timer } from "./timer.mjs";
|
|
3
3
|
|
|
4
4
|
//#region src/logger.d.ts
|
|
5
5
|
declare class Logger {
|
|
@@ -48,4 +48,4 @@ declare class Logger {
|
|
|
48
48
|
}
|
|
49
49
|
//#endregion
|
|
50
50
|
export { Logger };
|
|
51
|
-
//# sourceMappingURL=logger.d.
|
|
51
|
+
//# sourceMappingURL=logger.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logger.d.
|
|
1
|
+
{"version":3,"file":"logger.d.mts","names":[],"sources":["../src/logger.ts"],"sourcesContent":[],"mappings":";;;;cAca,MAAA;EAAA,QAAA,MAAM;EAOY,QAAA,SAAA;EAAR,QAAA,OAAA;EA2BgB,QAAA,MAAA;EAKH,QAAA,YAAA;EAKD,WAAA,CAAA,MAAA,CAAA,EArCZ,OAqCY,CArCJ,YAqCI,CAAA;EAKA,QAAA,CAAA,OAAA,EAAA,MAAA,EAAA,QAAA,CAAA,EAfI,MAeJ,CAAA,MAAA,EAAA,GAAA,CAAA,CAAA,EAAA,IAAA;EAKC,KAAA,CAAA,OAAA,EAAA,MAAA,EAAA,QAAA,CAAA,EAfA,MAeA,CAAA,MAAA,EAAA,GAAA,CAAA,CAAA,EAAA,IAAA;EAA6B,IAAA,CAAA,OAAA,EAAA,MAAA,EAAA,QAAA,CAAA,EAV9B,MAU8B,CAAA,MAAA,EAAA,GAAA,CAAA,CAAA,EAAA,IAAA;EAK7B,IAAA,CAAA,OAAA,EAAA,MAAA,EAAA,QAAA,CAAA,EAVD,MAUC,CAAA,MAAA,EAAA,GAAA,CAAA,CAAA,EAAA,IAAA;EAA6B,KAAA,CAAA,OAAA,E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,WAAR,CAAA,CAAA,EAAuB,MAAvB;EAAuB,QAAA,CAAA,KAAA,EAQtB,QARsB,CAAA,EAAA,IAAA;EAQtB,YAAA,CAAA,SAAA,EAIQ,SAJR,CAAA,EAAA,IAAA;EAIQ,OAAA,CAAA,CAAA,CAAA,CAAA,aAAA,EAAA,MAAA,EAAA,EAAA,EAAA,GAAA,GAOZ,CAPY,GAOR,OAPQ,CAOA,CAPA,CAAA,EAAA,OAOR,CAPQ,EAAA;IAOZ,SAAA,CAAA,EAAA,OAAA;IAAY,QAAA,CAAA,EACsB,QADtB;EAAR,CAAA,CAAA,EAEb,OAFa,CAEL,CAFK,CAAA;EAC8B,UAAA,CAAA,MAAA,EAAA,MAAA,EAAA,GAAA,EAAA,MAAA,EAAA,UAAA,CAAA,EAAA,MAAA,EAAA,QAAA,CAAA,EAAA,MAAA,CAAA,EAAA,IAAA;EACnC,KAAA,CAAA,CAAA,EA+DI,OA/DJ,CAAA,IAAA,CAAA;EAAR,QAAA,CAAA,CAAA,EAAA;IA+DY,YAAA,EAAA,MAAA;IAWL,WAAA,EAAA,MAAA;IAU+B,MAAA,EAV/B,YAU+B;EAAQ,CAAA;2CAAR"}
|
package/dist/logger.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{LogContext as e}from"./context.mjs";import{LogLevel as t}from"./types.mjs";import{TimerManager as n}from"./timer.mjs";import{Tracer as r}from"./tracer.mjs";import{DevFormatter as i,ProductionFormatter as a}from"./formatters.mjs";var o=class o{config;formatter;context;tracer;timerManager;constructor(o){this.config={level:t.INFO,environment:process.env.NODE_ENV||`development`,enableTracing:!0,enableTiming:!0,enableContext:!0,enableColors:!0,maxContextDepth:10,timestampFormat:`iso`,...o},this.context=e.getInstance(),this.tracer=new r,this.timerManager=new n,this.formatter=this.config.environment===`production`?new a:new i(this.config.enableColors)}traceLog(e,n){this.log(t.TRACE,e,n)}debug(e,n){this.log(t.DEBUG,e,n)}info(e,n){this.log(t.INFO,e,n)}warn(e,n){this.log(t.WARN,e,n)}error(e,n,r){this.log(t.ERROR,e,n,r)}fatal(e,n,r){this.log(t.FATAL,e,n,r)}withContext(e,t){return this.context.run(e,t)}extendContext(e,t){return this.context.extend(e,t)}setContext(e,t){this.context.set(e,t)}getContext(){return this.context.getContext()}trace=async(e,t)=>this.config.enableTracing?this.tracer.trace(e,t):await t();getTraceId(){return this.tracer.getCurrentTrace()?.traceId}startSpan(e){return this.config.enableTracing?this.tracer.startSpan(e):null}finishSpan(e){if(this.config.enableTracing)return this.tracer.finishSpan(e)}addTraceMetadata(e,t){this.config.enableTracing&&this.tracer.addMetadata(e,t)}addTraceTags(...e){this.config.enableTracing&&this.tracer.addTags(...e)}startTimer(e){return this.config.enableTiming?this.timerManager.start(e):null}stopTimer(e){if(this.config.enableTiming)return this.timerManager.stop(e)}getTimer(e){return this.timerManager.get(e)}child(e){let t=new o(this.config);return Object.entries(e).forEach(([e,n])=>{t.setContext(e,n)}),t}setLevel(e){this.config.level=e}setFormatter(e){this.formatter=e}async profile(e,n,r){let i=this.startTimer(`profile-${e}`),a=performance.now();try{let o=await this.tracer.trace({operationType:`custom`,operationName:`profile:${e}`,autoTiming:!0},n),s=performance.now()-a;i?.stop();let c=r?.logLevel||t.DEBUG;return this.log(c,`Profile: ${e} completed`,{operation:e,duration:`${s.toFixed(2)}ms`,result:r?.logResult?o:`[result hidden]`}),o}catch(t){let n=performance.now()-a;throw i?.stop(),this.error(`Profile: ${e} failed`,{operation:e,duration:`${n.toFixed(2)}ms`,error:t.message},t),t}}logRequest(e,t,n,r){let i=this.getHttpLogLevel(n),a=`${e.toUpperCase()} ${t}${n?` ${n}`:``}`;this.log(i,a,{method:e,url:t,statusCode:n,duration:r?`${r.toFixed(2)}ms`:void 0,type:`http_request`})}async flush(){this.timerManager.clear()}getStats(){return{activeTimers:this.timerManager.getActive().length,activeSpans:this.tracer.getActiveSpans().length,config:{...this.config}}}output(e,n){n>=t.ERROR?console.error(e):console.log(e)}log(e,t,n,r){if(e<this.config.level)return;let i=this.config.enableTracing?this.tracer.getCurrentTrace():void 0,a=this.config.enableContext?this.context.getContext():void 0,o={level:e,message:t,timestamp:new Date,traceId:i?.traceId,parentId:i?.parentId,spanId:i?.spanId,context:a,metadata:n,error:r,tags:i?.tags};i?.metadata?.duration&&(o.duration=i.metadata.duration);let s=this.formatter.format(o);this.output(s,e)}getHttpLogLevel(e){return e?e>=500?t.ERROR:e>=400?t.WARN:t.INFO:t.INFO}};export{o as Logger};
|
|
2
|
+
//# sourceMappingURL=logger.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logger.mjs","names":["entry: LogEntry"],"sources":["../src/logger.ts"],"sourcesContent":["import type {\n ContextData,\n Formatter,\n LogEntry,\n LoggerConfig,\n TraceMethod,\n TracingOptions,\n} from './types';\nimport { LogLevel } from './types';\nimport { LogContext } from './context';\nimport { Tracer } from './tracer';\nimport { Timer, TimerManager } from './timer';\nimport { DevFormatter, ProductionFormatter } from './formatters';\n\nexport class Logger {\n private config: LoggerConfig;\n private formatter: Formatter;\n private context: LogContext;\n private tracer: Tracer;\n private timerManager: TimerManager;\n\n constructor(config?: Partial<LoggerConfig>) {\n this.config = {\n level: LogLevel.INFO,\n environment:\n (process.env.NODE_ENV as LoggerConfig['environment']) || 'development',\n enableTracing: true,\n enableTiming: true,\n enableContext: true,\n enableColors: true,\n maxContextDepth: 10,\n timestampFormat: 'iso',\n ...config,\n };\n\n this.context = LogContext.getInstance();\n this.tracer = new Tracer();\n this.timerManager = new TimerManager();\n\n // Set up formatter based on environment\n this.formatter =\n this.config.environment === 'production'\n ? new ProductionFormatter()\n : new DevFormatter(this.config.enableColors);\n }\n\n // Core logging methods\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n traceLog(message: string, metadata?: Record<string, any>): void {\n this.log(LogLevel.TRACE, message, metadata);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n debug(message: string, metadata?: Record<string, any>): void {\n this.log(LogLevel.DEBUG, message, metadata);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n info(message: string, metadata?: Record<string, any>): void {\n this.log(LogLevel.INFO, message, metadata);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n warn(message: string, metadata?: Record<string, any>): void {\n this.log(LogLevel.WARN, message, metadata);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n error(message: string, metadata?: Record<string, any>, error?: Error): void {\n this.log(LogLevel.ERROR, message, metadata, error);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fatal(message: string, metadata?: Record<string, any>, error?: Error): void {\n this.log(LogLevel.FATAL, message, metadata, error);\n }\n\n // Context management\n withContext<T>(context: ContextData, fn: () => T): T {\n return this.context.run(context, fn);\n }\n\n extendContext<T>(additionalContext: Partial<ContextData>, fn: () => T): T {\n return this.context.extend(additionalContext, fn) as T;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n setContext(key: string, value: any): void {\n this.context.set(key, value);\n }\n\n getContext(): ContextData {\n return this.context.getContext();\n }\n\n // Tracing functionality\n trace: TraceMethod = async <T>(\n options: TracingOptions,\n fn: () => T | Promise<T>\n ): Promise<T> => {\n if (!this.config.enableTracing) {\n return await fn();\n }\n\n return this.tracer.trace(options, fn);\n };\n\n getTraceId(): string | undefined {\n return this.tracer.getCurrentTrace()?.traceId;\n }\n\n startSpan(options: TracingOptions) {\n if (!this.config.enableTracing) {\n return null;\n }\n return this.tracer.startSpan(options);\n }\n\n finishSpan(spanId: string): number | undefined {\n if (!this.config.enableTracing) {\n return undefined;\n }\n return this.tracer.finishSpan(spanId);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n addTraceMetadata(key: string, value: any): void {\n if (this.config.enableTracing) {\n this.tracer.addMetadata(key, value);\n }\n }\n\n addTraceTags(...tags: string[]): void {\n if (this.config.enableTracing) {\n this.tracer.addTags(...tags);\n }\n }\n\n // Timer functionality\n startTimer(id?: string): Timer | null {\n if (!this.config.enableTiming) {\n return null;\n }\n return this.timerManager.start(id);\n }\n\n stopTimer(id: string): number | undefined {\n if (!this.config.enableTiming) {\n return undefined;\n }\n return this.timerManager.stop(id);\n }\n\n getTimer(id: string): Timer | undefined {\n return this.timerManager.get(id);\n }\n\n // Utility methods\n child(context: Partial<ContextData>): Logger {\n const childLogger = new Logger(this.config);\n Object.entries(context).forEach(([key, value]) => {\n childLogger.setContext(key, value);\n });\n return childLogger;\n }\n\n setLevel(level: LogLevel): void {\n this.config.level = level;\n }\n\n setFormatter(formatter: Formatter): void {\n this.formatter = formatter;\n }\n\n // Performance profiling\n async profile<T>(\n operationName: string,\n fn: () => T | Promise<T>,\n options?: { logResult?: boolean; logLevel?: LogLevel }\n ): Promise<T> {\n const timer = this.startTimer(`profile-${operationName}`);\n const startTime = performance.now();\n\n try {\n const result = await this.tracer.trace(\n {\n operationType: 'custom',\n operationName: `profile:${operationName}`,\n autoTiming: true,\n },\n fn\n );\n\n const duration = performance.now() - startTime;\n timer?.stop();\n\n const logLevel = options?.logLevel || LogLevel.DEBUG;\n this.log(logLevel, `Profile: ${operationName} completed`, {\n operation: operationName,\n duration: `${duration.toFixed(2)}ms`,\n result: options?.logResult ? result : '[result hidden]',\n });\n\n return result;\n } catch (error) {\n const duration = performance.now() - startTime;\n timer?.stop();\n\n this.error(\n `Profile: ${operationName} failed`,\n {\n operation: operationName,\n duration: `${duration.toFixed(2)}ms`,\n error: (error as Error).message,\n },\n error as Error\n );\n\n throw error;\n }\n }\n\n // HTTP request logging helper\n logRequest(\n method: string,\n url: string,\n statusCode?: number,\n duration?: number\n ): void {\n const level = this.getHttpLogLevel(statusCode);\n const message = `${method.toUpperCase()} ${url}${statusCode ? ` ${statusCode}` : ''}`;\n\n this.log(level, message, {\n method,\n url,\n statusCode,\n duration: duration ? `${duration.toFixed(2)}ms` : undefined,\n type: 'http_request',\n });\n }\n\n // Flush any pending logs (useful for graceful shutdown)\n async flush(): Promise<void> {\n // In a more advanced implementation, this might flush to external systems\n // For now, it just clears internal state\n this.timerManager.clear();\n // this.tracer.clear();\n }\n\n // Get logger statistics\n getStats(): {\n activeTimers: number;\n activeSpans: number;\n config: LoggerConfig;\n } {\n return {\n activeTimers: this.timerManager.getActive().length,\n activeSpans: this.tracer.getActiveSpans().length,\n config: { ...this.config },\n };\n }\n\n // Output method (can be overridden for custom outputs)\n protected output(message: string, level: LogLevel): void {\n if (level >= LogLevel.ERROR) {\n console.error(message);\n } else {\n console.log(message);\n }\n }\n\n // Core log method\n private log(\n level: LogLevel,\n message: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata?: Record<string, any>,\n error?: Error\n ): void {\n if (level < this.config.level) {\n return; // Skip logs below configured level\n }\n\n const currentTrace = this.config.enableTracing\n ? this.tracer.getCurrentTrace()\n : undefined;\n const contextData = this.config.enableContext\n ? this.context.getContext()\n : undefined;\n\n const entry: LogEntry = {\n level,\n message,\n timestamp: new Date(),\n traceId: currentTrace?.traceId,\n parentId: currentTrace?.parentId,\n spanId: currentTrace?.spanId,\n context: contextData,\n metadata,\n error,\n tags: currentTrace?.tags,\n };\n\n // Add duration if we're in a traced operation\n if (currentTrace?.metadata?.duration) {\n entry.duration = currentTrace.metadata.duration as number;\n }\n\n const formatted = this.formatter.format(entry);\n this.output(formatted, level);\n }\n\n private getHttpLogLevel(statusCode?: number): LogLevel {\n if (!statusCode) return LogLevel.INFO;\n if (statusCode >= 500) return LogLevel.ERROR;\n if (statusCode >= 400) return LogLevel.WARN;\n return LogLevel.INFO;\n }\n}\n"],"mappings":"4OAcA,IAAa,EAAb,MAAa,CAAO,CAClB,OACA,UACA,QACA,OACA,aAEA,YAAY,EAAgC,CAC1C,KAAK,OAAS,CACZ,MAAO,EAAS,KAChB,YACG,QAAQ,IAAI,UAA4C,cAC3D,cAAe,GACf,aAAc,GACd,cAAe,GACf,aAAc,GACd,gBAAiB,GACjB,gBAAiB,MACjB,GAAG,EACJ,CAED,KAAK,QAAU,EAAW,aAAa,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.d.ts
|
|
4
4
|
declare class Timer implements Timer$1 {
|
|
@@ -100,4 +100,4 @@ declare function timedSync<T>(operation: () => T, options?: {
|
|
|
100
100
|
};
|
|
101
101
|
//#endregion
|
|
102
102
|
export { Timer, TimerManager, timed, timedSync };
|
|
103
|
-
//# sourceMappingURL=timer.d.
|
|
103
|
+
//# sourceMappingURL=timer.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"timer.d.
|
|
1
|
+
{"version":3,"file":"timer.d.mts","names":[],"sources":["../src/timer.ts"],"sourcesContent":[],"mappings":";;;cAEa,KAAA,YAAiB;;EAAjB,QAAM,SAAA;EAqGN,QAAA,IAAA;EAMS,QAAA,OAAA;EASH,QAAA,QAAA;EAoBJ,WAAA,CAAA,EAAA,CAAA,EAAA,MAAA;EAgBY;;;EAQL,IAAA,CAAA,CAAA,EAAK,MAAA;EACA;;;EAEqB,GAAA,CAAA,KAAA,CAAA,EAAA,MAAA,CAAA,EAAA,MAAA;EAA7C;;AAmBH;EACmB,UAAA,CAAA,CAAA,EAAA,MAAA;EAEN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cApFA,YAAA;;;;;sBAMS;;;;mBASH;;;;;;;;eAoBJ;;;;;;;;gBAgBC,WAAW;;;;;iBAQL,0BACH,QAAQ;;;IAExB;UAAkB;;SAA2B;;;;;iBAmBhC,8BACG;;;;UAEN;;SAA2B"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var e=class{id;startTime;laps=[];stopped=!1;stopTime;constructor(e){this.id=e||crypto.randomUUID(),this.startTime=performance.now()}stop(){if(this.stopped)return this.getElapsed();this.stopTime=performance.now(),this.stopped=!0;let e=this.stopTime-this.startTime;return this.laps.push({label:`stop`,time:this.stopTime,elapsed:e}),e}lap(e){if(this.stopped)return this.getElapsed();let t=performance.now(),n=t-this.startTime;return this.laps.push({label:e||`lap-${this.laps.length+1}`,time:t,elapsed:n}),n}getElapsed(){return this.stopped&&this.stopTime?this.stopTime-this.startTime:performance.now()-this.startTime}getLaps(){return[...this.laps]}getSummary(){return{id:this.id,totalTime:this.getElapsed(),isRunning:!this.stopped,laps:this.getLaps()}}reset(){this.startTime=performance.now(),this.laps=[],this.stopped=!1,this.stopTime=void 0}},t=class{timers=new Map;start(t){let n=new e(t);return this.timers.set(n.id,n),n}get(e){return this.timers.get(e)}stop(e){let t=this.timers.get(e);if(t){let n=t.stop();return this.timers.delete(e),n}}getActive(){return Array.from(this.timers.values()).filter(e=>!!e.getSummary().isRunning)}clear(){this.timers.clear()}getSummary(){return Array.from(this.timers.values()).map(e=>e.getSummary())}};async function n(t,n){let r=new e(n?.id);try{let e=await t(),i=r.stop();return n?.onComplete?.(i),{result:e,elapsed:i,timer:r}}catch(e){throw r.stop(),e}}function r(t,n){let r=new e(n?.id);try{let e=t(),i=r.stop();return n?.onComplete?.(i),{result:e,elapsed:i,timer:r}}catch(e){throw r.stop(),e}}export{e as Timer,t as TimerManager,n as timed,r as timedSync};
|
|
2
|
-
//# sourceMappingURL=timer.
|
|
2
|
+
//# sourceMappingURL=timer.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"timer.mjs","names":[],"sources":["../src/timer.ts"],"sourcesContent":["import type { Timer as ITimer } from './types';\n\nexport class Timer implements ITimer {\n readonly id: string;\n private startTime: number;\n private laps: { label?: string; time: number; elapsed: number }[] = [];\n private stopped = false;\n private stopTime?: number;\n\n constructor(id?: string) {\n this.id = id || crypto.randomUUID();\n this.startTime = performance.now();\n }\n\n /**\n * Stop the timer and return elapsed time in milliseconds\n */\n stop(): number {\n if (this.stopped) {\n return this.getElapsed();\n }\n\n this.stopTime = performance.now();\n this.stopped = true;\n const elapsed = this.stopTime - this.startTime;\n\n this.laps.push({\n label: 'stop',\n time: this.stopTime,\n elapsed,\n });\n\n return elapsed;\n }\n\n /**\n * Record a lap time and return elapsed time since start\n */\n lap(label?: string): number {\n if (this.stopped) {\n return this.getElapsed();\n }\n\n const now = performance.now();\n const elapsed = now - this.startTime;\n\n this.laps.push({\n label: label || `lap-${this.laps.length + 1}`,\n time: now,\n elapsed,\n });\n\n return elapsed;\n }\n\n /**\n * Get elapsed time without stopping the timer\n */\n getElapsed(): number {\n if (this.stopped && this.stopTime) {\n return this.stopTime - this.startTime;\n }\n return performance.now() - this.startTime;\n }\n\n /**\n * Get all recorded laps\n */\n getLaps(): { label?: string; time: number; elapsed: number }[] {\n return [...this.laps];\n }\n\n /**\n * Get timer summary with total time and laps\n */\n getSummary(): {\n id: string;\n totalTime: number;\n isRunning: boolean;\n laps: { label?: string; time: number; elapsed: number }[];\n } {\n return {\n id: this.id,\n totalTime: this.getElapsed(),\n isRunning: !this.stopped,\n laps: this.getLaps(),\n };\n }\n\n /**\n * Reset the timer (starts a new timing session)\n */\n reset(): void {\n this.startTime = performance.now();\n this.laps = [];\n this.stopped = false;\n this.stopTime = undefined;\n }\n}\n\n/**\n * Utility class for managing multiple timers\n */\nexport class TimerManager {\n private timers = new Map<string, Timer>();\n\n /**\n * Start a new timer\n */\n start(id?: string): Timer {\n const timer = new Timer(id);\n this.timers.set(timer.id, timer);\n return timer;\n }\n\n /**\n * Get an existing timer\n */\n get(id: string): Timer | undefined {\n return this.timers.get(id);\n }\n\n /**\n * Stop and remove a timer\n */\n stop(id: string): number | undefined {\n const timer = this.timers.get(id);\n if (timer) {\n const elapsed = timer.stop();\n this.timers.delete(id);\n return elapsed;\n }\n return undefined;\n }\n\n /**\n * Get all active timers\n */\n getActive(): Timer[] {\n return Array.from(this.timers.values()).filter(\n (timer) => !timer.getSummary().isRunning === false\n );\n }\n\n /**\n * Clear all timers\n */\n clear(): void {\n this.timers.clear();\n }\n\n /**\n * Get summary of all timers\n */\n getSummary(): ReturnType<Timer['getSummary']>[] {\n return Array.from(this.timers.values()).map((timer) => timer.getSummary());\n }\n}\n\n/**\n * Decorator/wrapper function to time async operations\n */\nexport async function timed<T>(\n operation: () => Promise<T>,\n options?: { id?: string; onComplete?: (elapsed: number) => void }\n): Promise<{ result: T; elapsed: number; timer: Timer }> {\n const timer = new Timer(options?.id);\n\n try {\n const result = await operation();\n const elapsed = timer.stop();\n\n options?.onComplete?.(elapsed);\n\n return { result, elapsed, timer };\n } catch (error) {\n timer.stop();\n throw error;\n }\n}\n\n/**\n * Decorator/wrapper function to time synchronous operations\n */\nexport function timedSync<T>(\n operation: () => T,\n options?: { id?: string; onComplete?: (elapsed: number) => void }\n): { result: T; elapsed: number; timer: Timer } {\n const timer = new Timer(options?.id);\n\n try {\n const result = operation();\n const elapsed = timer.stop();\n\n options?.onComplete?.(elapsed);\n\n return { result, elapsed, timer };\n } catch (error) {\n timer.stop();\n throw error;\n }\n}\n"],"mappings":"AAEA,IAAa,EAAb,KAAqC,CACnC,GACA,UACA,KAAoE,EAAE,CACtE,QAAkB,GAClB,SAEA,YAAY,EAAa,CACvB,KAAK,GAAK,GAAM,OAAO,YAAY,CACnC,KAAK,UAAY,YAAY,KAAK,CAMpC,MAAe,CACb,GAAI,KAAK,QACP,OAAO,KAAK,YAAY,CAG1B,KAAK,SAAW,YAAY,KAAK,CACjC,KAAK,QAAU,GACf,IAAM,EAAU,KAAK,SAAW,KAAK,UAQrC,OANA,KAAK,KAAK,KAAK,CACb,MAAO,OACP,KAAM,KAAK,SACX,UACD,CAAC,CAEK,EAMT,IAAI,EAAwB,CAC1B,GAAI,KAAK,QACP,OAAO,KAAK,YAAY,CAG1B,IAAM,EAAM,YAAY,KAAK,CACvB,EAAU,EAAM,KAAK,UAQ3B,OANA,KAAK,KAAK,KAAK,CACb,MAAO,GAAS,OAAO,KAAK,KAAK,OAAS,IAC1C,KAAM,EACN,UACD,CAAC,CAEK,EAMT,YAAqB,CAInB,OAHI,KAAK,SAAW,KAAK,SAChB,KAAK,SAAW,KAAK,UAEvB,YAAY,KAAK,CAAG,KAAK,UAMlC,SAA+D,CAC7D,MAAO,CAAC,GAAG,KAAK,KAAK,CAMvB,YAKE,CACA,MAAO,CACL,GAAI,KAAK,GACT,UAAW,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,EAAO,CAEd,MADA,EAAM,MAAM,CACN"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { TraceContext, TracingOptions } from "./types.
|
|
1
|
+
import { TraceContext, TracingOptions } from "./types.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/tracer.d.ts
|
|
4
4
|
declare class Tracer {
|
|
@@ -48,4 +48,4 @@ declare class Tracer {
|
|
|
48
48
|
}
|
|
49
49
|
//#endregion
|
|
50
50
|
export { Tracer };
|
|
51
|
-
//# sourceMappingURL=tracer.d.
|
|
51
|
+
//# sourceMappingURL=tracer.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tracer.d.
|
|
1
|
+
{"version":3,"file":"tracer.d.mts","names":[],"sources":["../src/tracer.ts"],"sourcesContent":[],"mappings":";;;cAIa,MAAA;;EAAA,QAAA,WAAM;EAWE,WAAA,CAAA;EAAiB;;;EAkDZ,SAAA,CAAA,OAAA,EAlDL,cAkDK,CAAA,EAlDY,YAkDZ;EAAR;;;EAgEG,UAAA,CAAA,MAAA,EAAA,MAAA,CAAA,EAAA,MAAA,GAAA,SAAA;EAOD;;;oBAxEP,0BACC,IAAI,QAAQ,KACrB,QAAQ;;;;;;;;;;;;qBA+DQ;;;;oBAOD;;;;gCAOY"}
|
package/dist/tracer.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{LogContext as e}from"./context.mjs";import{Timer as t}from"./timer.mjs";var n=class{context;activeSpans=new Map;constructor(){this.context=e.getInstance()}startSpan(e){let t=this.context.getCurrentTrace(),n={traceId:t?.traceId||this.generateTraceId(),parentId:t?.spanId,spanId:this.generateSpanId(),operationType:e.operationType,operationName:e.operationName,startTime:performance.now(),metadata:{...e.metadata},tags:[...e.tags||[]]};return this.activeSpans.set(n.spanId,n),this.context.setTrace(n),n}finishSpan(e){let t=this.activeSpans.get(e);if(!t)return;let n=performance.now()-t.startTime;if(this.activeSpans.delete(e),this.context.getCurrentTrace()?.spanId===e&&t.parentId){let e=this.findSpanById(t.parentId);e&&this.context.setTrace(e)}return n}async trace(e,n){let r=this.startSpan(e),i=e.autoTiming===!1?void 0:new t(`trace-${r.spanId}`);try{let e=await n(),t=this.finishSpan(r.spanId);return i&&i.stop(),t!==void 0&&(r.metadata.duration=t),e}catch(e){r.metadata.error={name:e.name||`Unknown`,message:e.message||`Unknown error`,stack:e.stack};let t=this.finishSpan(r.spanId);throw r.metadata.duration=t,i&&i.stop(),e}}addMetadata(e,t){let n=this.context.getCurrentTrace();n&&(n.metadata[e]=t)}addTags(...e){let t=this.context.getCurrentTrace();t&&t.tags.push(...e)}getCurrentTrace(){return this.context.getCurrentTrace()}getActiveSpans(){return Array.from(this.activeSpans.values())}findSpanById(e){return this.activeSpans.get(e)}generateTraceId(){return crypto.randomUUID().replace(/-/g,``)}generateSpanId(){return crypto.randomUUID().replace(/-/g,``).substring(0,16)}};export{n as Tracer};
|
|
2
|
+
//# sourceMappingURL=tracer.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tracer.mjs","names":["span: TraceContext"],"sources":["../src/tracer.ts"],"sourcesContent":["import type { TraceContext, TracingOptions } from './types';\nimport { LogContext } from './context';\nimport { Timer } from './timer';\n\nexport class Tracer {\n private context: LogContext;\n private activeSpans = new Map<string, TraceContext>();\n\n constructor() {\n this.context = LogContext.getInstance();\n }\n\n /**\n * Start a new trace span\n */\n startSpan(options: TracingOptions): TraceContext {\n const parentTrace = this.context.getCurrentTrace();\n const traceId = parentTrace?.traceId || this.generateTraceId();\n\n const span: TraceContext = {\n traceId,\n parentId: parentTrace?.spanId,\n spanId: this.generateSpanId(),\n operationType: options.operationType,\n operationName: options.operationName,\n startTime: performance.now(),\n metadata: { ...options.metadata },\n tags: [...(options.tags || [])],\n };\n\n this.activeSpans.set(span.spanId, span);\n this.context.setTrace(span);\n\n return span;\n }\n\n /**\n * Finish a trace span\n */\n finishSpan(spanId: string): number | undefined {\n const span = this.activeSpans.get(spanId);\n if (!span) {\n return undefined;\n }\n\n const duration = performance.now() - span.startTime;\n this.activeSpans.delete(spanId);\n\n // If this was the current span, restore parent\n const currentTrace = this.context.getCurrentTrace();\n if (currentTrace?.spanId === spanId && span.parentId) {\n const parentSpan = this.findSpanById(span.parentId);\n if (parentSpan) {\n this.context.setTrace(parentSpan);\n }\n }\n\n return duration;\n }\n\n /**\n * Execute a function within a trace span\n */\n async trace<T>(\n options: TracingOptions,\n fn: () => T | Promise<T>\n ): Promise<T> {\n const span = this.startSpan(options);\n const timer =\n options.autoTiming !== false\n ? new Timer(`trace-${span.spanId}`)\n : undefined;\n\n try {\n const result = await fn();\n\n const duration = this.finishSpan(span.spanId);\n if (timer) {\n timer.stop();\n }\n\n // Add timing metadata\n if (duration !== undefined) {\n span.metadata.duration = duration;\n }\n\n return result;\n } catch (error) {\n // Add error metadata\n span.metadata.error = {\n name: (error as Error).name || 'Unknown',\n message: (error as Error).message || 'Unknown error',\n stack: (error as Error).stack,\n };\n\n const duration = this.finishSpan(span.spanId);\n span.metadata.duration = duration;\n if (timer) {\n timer.stop();\n }\n\n throw error;\n }\n }\n\n /**\n * Add metadata to current span\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n addMetadata(key: string, value: any): void {\n const currentTrace = this.context.getCurrentTrace();\n if (currentTrace) {\n currentTrace.metadata[key] = value;\n }\n }\n\n /**\n * Add tags to current span\n */\n addTags(...tags: string[]): void {\n const currentTrace = this.context.getCurrentTrace();\n if (currentTrace) {\n currentTrace.tags.push(...tags);\n }\n }\n\n /**\n * Get current trace context\n */\n getCurrentTrace(): TraceContext | undefined {\n return this.context.getCurrentTrace();\n }\n\n /**\n * Get all active spans\n */\n getActiveSpans(): TraceContext[] {\n return Array.from(this.activeSpans.values());\n }\n\n /**\n * Find a span by ID\n */\n findSpanById(spanId: string): TraceContext | undefined {\n return this.activeSpans.get(spanId);\n }\n\n /**\n * Generate a unique trace ID\n */\n private generateTraceId(): string {\n return crypto.randomUUID().replace(/-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CAEd,EAAK,SAAS,MAAQ,CACpB,KAAO,EAAgB,MAAQ,UAC/B,QAAU,EAAgB,SAAW,gBACrC,MAAQ,EAAgB,MACzB,CAED,IAAM,EAAW,KAAK,WAAW,EAAK,OAAO,CAM7C,KALA,GAAK,SAAS,SAAW,EACrB,GACF,EAAM,MAAM,CAGR,GAQV,YAAY,EAAa,EAAkB,CACzC,IAAM,EAAe,KAAK,QAAQ,iBAAiB,CAC/C,IACF,EAAa,SAAS,GAAO,GAOjC,QAAQ,GAAG,EAAsB,CAC/B,IAAM,EAAe,KAAK,QAAQ,iBAAiB,CAC/C,GACF,EAAa,KAAK,KAAK,GAAG,EAAK,CAOnC,iBAA4C,CAC1C,OAAO,KAAK,QAAQ,iBAAiB,CAMvC,gBAAiC,CAC/B,OAAO,MAAM,KAAK,KAAK,YAAY,QAAQ,CAAC,CAM9C,aAAa,EAA0C,CACrD,OAAO,KAAK,YAAY,IAAI,EAAO,CAMrC,iBAAkC,CAChC,OAAO,OAAO,YAAY,CAAC,QAAQ,KAAM,GAAG,CAM9C,gBAAiC,CAC/B,OAAO,OAAO,YAAY,CAAC,QAAQ,KAAM,GAAG,CAAC,UAAU,EAAG,GAAG"}
|
|
@@ -68,4 +68,4 @@ type LogMethod = (message: string, metadata?: Record<string, any>) => void;
|
|
|
68
68
|
type TraceMethod = <T>(options: TracingOptions, fn: () => T | Promise<T>) => Promise<T>;
|
|
69
69
|
//#endregion
|
|
70
70
|
export { ContextData, Formatter, LogEntry, LogLevel, LogMethod, LoggerConfig, Timer, TraceContext, TraceMethod, TracingOptions };
|
|
71
|
-
//# sourceMappingURL=types.d.
|
|
71
|
+
//# sourceMappingURL=types.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.
|
|
1
|
+
{"version":3,"file":"types.d.mts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";aAAY,QAAA;EAAA,KAAA,GAAA,CAAA;EASK,KAAA,GAAA,CAAA;EACR,IAAA,GAAA,CAAA;EAEI,IAAA,GAAA,CAAA;EAKD,KAAA,GAAA,CAAA;EAEC,KAAA,GAAA,CAAA;;AAEE,UAZE,QAAA,CAYF;EAIE,KAAA,EAfR,QAeoB;EAYZ,OAAA,EAAA,MAAA;EAeA,SAAA,EAxCJ,IAwCgB;EAWZ,OAAA,CAAA,EAAA,MAAS;EAIT,QAAK,CAAA,EAAA,MAAA;EAQL,MAAA,CAAA,EAAA,MAAW;EAUhB,OAAA,CAAA,EApEA,MAoES,CAAA,MAAA,EAGR,GAAA,CAAA;EAED,QAAA,CAAA,EAvEC,MAuEU,CAAA,MAAA,EAAA,GAAA,CAAA;EACZ,QAAA,CAAA,EAAA,MAAA;EACC,KAAA,CAAA,EAvEF,KAuEE;EAAY,IAAA,CAAA,EAAA,MAAA,EAAA;;AACX,UApEI,YAAA,CAoEJ;EAAR,OAAA,EAAA,MAAA;EAAO,QAAA,CAAA,EAAA,MAAA;;;;;YA5DA;;;UAIK,cAAA;;;aAUJ;;;;UAKI,YAAA;SACR;;;;;;;;;UAUQ,SAAA;gBACD;;UAGC,KAAA;;;;;;UAQA,WAAA;;;;;;;;KAUL,SAAA,gCAGC;KAED,WAAA,gBACD,0BACC,IAAI,QAAQ,OACnB,QAAQ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
let e=function(e){return e[e.TRACE=0]=`TRACE`,e[e.DEBUG=1]=`DEBUG`,e[e.INFO=2]=`INFO`,e[e.WARN=3]=`WARN`,e[e.ERROR=4]=`ERROR`,e[e.FATAL=5]=`FATAL`,e}({});export{e as LogLevel};
|
|
2
|
-
//# sourceMappingURL=types.
|
|
2
|
+
//# sourceMappingURL=types.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.mjs","names":[],"sources":["../src/types.ts"],"sourcesContent":["export enum LogLevel {\n TRACE = 0,\n DEBUG = 1,\n INFO = 2,\n WARN = 3,\n ERROR = 4,\n FATAL = 5,\n}\n\nexport interface LogEntry {\n level: LogLevel;\n message: string;\n timestamp: Date;\n traceId?: string;\n parentId?: string;\n spanId?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n context?: Record<string, any>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata?: Record<string, any>;\n duration?: number;\n error?: Error;\n tags?: string[];\n}\n\nexport interface TraceContext {\n traceId: string;\n parentId?: string;\n spanId: string;\n operationType: string;\n operationName: string;\n startTime: number;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n tags: string[];\n}\n\nexport interface TracingOptions {\n operationType:\n | 'http'\n | 'websocket'\n | 'cron'\n | 'queue'\n | 'database'\n | 'custom';\n operationName: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata?: Record<string, any>;\n tags?: string[];\n autoTiming?: boolean;\n}\n\nexport interface LoggerConfig {\n level: LogLevel;\n environment: 'development' | 'production' | 'test';\n enableTracing: boolean;\n enableTiming: boolean;\n enableContext: boolean;\n enableColors: boolean;\n maxContextDepth: number;\n timestampFormat: 'iso' | 'epoch' | 'relative';\n}\n\nexport interface Formatter {\n format(entry: LogEntry): string;\n}\n\nexport interface Timer {\n readonly id: string;\n // private startTime: number;\n stop(): number;\n lap(label?: string): number;\n getElapsed(): number;\n}\n\nexport interface ContextData {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n userId?: string;\n requestId?: string;\n sessionId?: string;\n ip?: string;\n userAgent?: string;\n}\n\nexport type LogMethod = (\n message: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata?: Record<string, any>\n) => void;\nexport type TraceMethod = <T>(\n options: TracingOptions,\n fn: () => T | Promise<T>\n) => Promise<T>;\n"],"mappings":"AAAA,IAAY,EAAA,SAAA,EAAL,OACL,GAAA,EAAA,MAAA,GAAA,QACA,EAAA,EAAA,MAAA,GAAA,QACA,EAAA,EAAA,KAAA,GAAA,OACA,EAAA,EAAA,KAAA,GAAA,OACA,EAAA,EAAA,MAAA,GAAA,QACA,EAAA,EAAA,MAAA,GAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lssm/lib.logger",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.9.0",
|
|
4
4
|
"description": "Comprehensive logging library optimized for Bun with ElysiaJS integration",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"logging",
|
|
@@ -21,9 +21,9 @@
|
|
|
21
21
|
"dev": "bun build:bundle --watch"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
|
-
"@lssm/tool.typescript": "
|
|
25
|
-
"@lssm/tool.tsdown": "
|
|
26
|
-
"tsdown": "^0.
|
|
24
|
+
"@lssm/tool.typescript": "workspace:*",
|
|
25
|
+
"@lssm/tool.tsdown": "workspace:*",
|
|
26
|
+
"tsdown": "^0.16.6",
|
|
27
27
|
"typescript": "^5.9.3"
|
|
28
28
|
},
|
|
29
29
|
"peerDependencies": {
|
|
@@ -34,46 +34,22 @@
|
|
|
34
34
|
"optional": true
|
|
35
35
|
}
|
|
36
36
|
},
|
|
37
|
-
"main": "./dist/index.
|
|
38
|
-
"types": "./dist/index.d.
|
|
37
|
+
"main": "./dist/index.mjs",
|
|
38
|
+
"types": "./dist/index.d.mts",
|
|
39
39
|
"files": [
|
|
40
40
|
"dist",
|
|
41
41
|
"README.md"
|
|
42
42
|
],
|
|
43
43
|
"exports": {
|
|
44
|
-
".":
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
"./
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
"./elysia-plugin": {
|
|
53
|
-
"import": "./dist/elysia-plugin.js",
|
|
54
|
-
"require": "./dist/elysia-plugin.cjs"
|
|
55
|
-
},
|
|
56
|
-
"./formatters": {
|
|
57
|
-
"import": "./dist/formatters.js",
|
|
58
|
-
"require": "./dist/formatters.cjs"
|
|
59
|
-
},
|
|
60
|
-
"./logger": {
|
|
61
|
-
"import": "./dist/logger.js",
|
|
62
|
-
"require": "./dist/logger.cjs"
|
|
63
|
-
},
|
|
64
|
-
"./timer": {
|
|
65
|
-
"import": "./dist/timer.js",
|
|
66
|
-
"require": "./dist/timer.cjs"
|
|
67
|
-
},
|
|
68
|
-
"./tracer": {
|
|
69
|
-
"import": "./dist/tracer.js",
|
|
70
|
-
"require": "./dist/tracer.cjs"
|
|
71
|
-
},
|
|
72
|
-
"./types": {
|
|
73
|
-
"import": "./dist/types.js",
|
|
74
|
-
"require": "./dist/types.cjs"
|
|
75
|
-
},
|
|
44
|
+
".": "./dist/index.mjs",
|
|
45
|
+
"./context": "./dist/context.mjs",
|
|
46
|
+
"./elysia-plugin": "./dist/elysia-plugin.mjs",
|
|
47
|
+
"./formatters": "./dist/formatters.mjs",
|
|
48
|
+
"./logger": "./dist/logger.mjs",
|
|
49
|
+
"./timer": "./dist/timer.mjs",
|
|
50
|
+
"./tracer": "./dist/tracer.mjs",
|
|
51
|
+
"./types": "./dist/types.mjs",
|
|
76
52
|
"./*": "./*"
|
|
77
53
|
},
|
|
78
|
-
"module": "./dist/index.
|
|
54
|
+
"module": "./dist/index.mjs"
|
|
79
55
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));exports.__toESM=s;
|
package/dist/context.cjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e=require(`./_virtual/rolldown_runtime.cjs`);let t=require(`node:async_hooks`);t=e.__toESM(t);var n=class e{static instance;storage;constructor(){this.storage=new t.AsyncLocalStorage}static getInstance(){return e.instance||=new e,e.instance}run(e,t){let n={context:{...e},trace:this.getCurrentTrace()};return this.storage.run(n,t)}extend(e,t){let n={...this.getContext(),...e};return this.run(n,t)}set(e,t){let n=this.storage.getStore();n&&(n.context[e]=t)}get(e){return this.storage.getStore()?.context?.[e]}getContext(){return this.storage.getStore()?.context||{}}setTrace(e){let t=this.storage.getStore();t&&(t.trace=e)}getCurrentTrace(){return this.storage.getStore()?.trace}generateId(){return crypto.randomUUID()}};exports.LogContext=n;
|
package/dist/context.d.cts
DELETED
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
import { ContextData, TraceContext } from "./types.cjs";
|
|
2
|
-
|
|
3
|
-
//#region src/context.d.ts
|
|
4
|
-
declare class LogContext {
|
|
5
|
-
private static instance;
|
|
6
|
-
private storage;
|
|
7
|
-
constructor();
|
|
8
|
-
static getInstance(): LogContext;
|
|
9
|
-
/**
|
|
10
|
-
* Run a function with a new context
|
|
11
|
-
*/
|
|
12
|
-
run<T>(context: ContextData, fn: () => T): T;
|
|
13
|
-
/**
|
|
14
|
-
* Run a function with an extended context (merges with current)
|
|
15
|
-
*/
|
|
16
|
-
extend<T>(additionalContext: Partial<ContextData>, fn: () => T): T;
|
|
17
|
-
/**
|
|
18
|
-
* Set context data for the current execution context
|
|
19
|
-
*/
|
|
20
|
-
set(key: string, value: any): void;
|
|
21
|
-
/**
|
|
22
|
-
* Get a specific context value
|
|
23
|
-
*/
|
|
24
|
-
get<T>(key: string): T | undefined;
|
|
25
|
-
/**
|
|
26
|
-
* Get all context data
|
|
27
|
-
*/
|
|
28
|
-
getContext(): ContextData;
|
|
29
|
-
/**
|
|
30
|
-
* Set trace context
|
|
31
|
-
*/
|
|
32
|
-
setTrace(trace: TraceContext): void;
|
|
33
|
-
/**
|
|
34
|
-
* Get current trace context
|
|
35
|
-
*/
|
|
36
|
-
getCurrentTrace(): TraceContext | undefined;
|
|
37
|
-
/**
|
|
38
|
-
* Generate a unique ID for requests/operations
|
|
39
|
-
*/
|
|
40
|
-
generateId(): string;
|
|
41
|
-
}
|
|
42
|
-
//#endregion
|
|
43
|
-
export { LogContext };
|
|
44
|
-
//# sourceMappingURL=context.d.cts.map
|
package/dist/context.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"context.d.ts","names":[],"sources":["../src/context.ts"],"sourcesContent":[],"mappings":";;;cAQa,UAAA;;EAAA,QAAA,OAAU;EAQC,WAAA,CAAA;EAUN,OAAA,WAAA,CAAA,CAAA,EAVM,UAUN;EAAuB;;;EAWV,GAAA,CAAA,CAAA,CAAA,CAAA,OAAA,EAXb,WAWa,EAAA,EAAA,EAAA,GAAA,GAXU,CAWV,CAAA,EAXc,CAWd;EAAgC;;;EA+B/C,MAAA,CAAA,CAAA,CAAA,CAAA,iBAAA,EA/Be,OA+Bf,CA/BuB,WA+BvB,CAAA,EAAA,EAAA,EAAA,GAAA,GA/B+C,CA+B/C,CAAA,EA/BmD,CA+BnD;EAQE;;;;;;;uBAhBK;;;;gBAQP;;;;kBAQE;;;;qBAUG"}
|
package/dist/context.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"context.js","names":["contextData: LogContextData","mergedContext: ContextData"],"sources":["../src/context.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { ContextData, TraceContext } from './types';\n\ninterface LogContextData {\n context: ContextData;\n trace?: TraceContext;\n}\n\nexport class LogContext {\n private static instance: LogContext;\n private storage: AsyncLocalStorage<LogContextData>;\n\n constructor() {\n this.storage = new AsyncLocalStorage<LogContextData>();\n }\n\n static getInstance(): LogContext {\n if (!LogContext.instance) {\n LogContext.instance = new LogContext();\n }\n return LogContext.instance;\n }\n\n /**\n * Run a function with a new context\n */\n run<T>(context: ContextData, fn: () => T): T {\n const contextData: LogContextData = {\n context: { ...context },\n trace: this.getCurrentTrace(),\n };\n return this.storage.run(contextData, fn) as T;\n }\n\n /**\n * Run a function with an extended context (merges with current)\n */\n extend<T>(additionalContext: Partial<ContextData>, fn: () => T): T {\n const currentContext = this.getContext();\n const mergedContext: ContextData = {\n ...currentContext,\n ...additionalContext,\n };\n return this.run(mergedContext, fn);\n }\n\n /**\n * Set context data for the current execution context\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n set(key: string, value: any): void {\n const current = this.storage.getStore();\n if (current) {\n current.context[key] = value;\n }\n }\n\n /**\n * Get a specific context value\n */\n get<T>(key: string): T | undefined {\n const current = this.storage.getStore();\n return current?.context?.[key];\n }\n\n /**\n * Get all context data\n */\n getContext(): ContextData {\n const current = this.storage.getStore();\n return current?.context || {};\n }\n\n /**\n * Set trace context\n */\n setTrace(trace: TraceContext): void {\n const current = this.storage.getStore();\n if (current) {\n current.trace = trace;\n }\n }\n\n /**\n * Get current trace context\n */\n getCurrentTrace(): TraceContext | undefined {\n const current = this.storage.getStore();\n return current?.trace;\n }\n /**\n * Generate a unique ID for requests/operations\n */\n generateId(): string {\n return crypto.randomUUID();\n }\n}\n"],"mappings":"qDAQA,IAAa,EAAb,MAAa,CAAW,CACtB,OAAe,SACf,QAEA,aAAc,CACZ,KAAK,QAAU,IAAI,EAGrB,OAAO,aAA0B,CAI/B,MAHA,CACE,EAAW,WAAW,IAAI,EAErB,EAAW,SAMpB,IAAO,EAAsB,EAAgB,CAC3C,IAAMA,EAA8B,CAClC,QAAS,CAAE,GAAG,EAAS,CACvB,MAAO,KAAK,iBAAiB,CAC9B,CACD,OAAO,KAAK,QAAQ,IAAI,EAAa,EAAG,CAM1C,OAAU,EAAyC,EAAgB,CAEjE,IAAMC,EAA6B,CACjC,GAFqB,KAAK,YAAY,CAGtC,GAAG,EACJ,CACD,OAAO,KAAK,IAAI,EAAe,EAAG,CAOpC,IAAI,EAAa,EAAkB,CACjC,IAAM,EAAU,KAAK,QAAQ,UAAU,CACnC,IACF,EAAQ,QAAQ,GAAO,GAO3B,IAAO,EAA4B,CAEjC,OADgB,KAAK,QAAQ,UAAU,EACvB,UAAU,GAM5B,YAA0B,CAExB,OADgB,KAAK,QAAQ,UAAU,EACvB,SAAW,EAAE,CAM/B,SAAS,EAA2B,CAClC,IAAM,EAAU,KAAK,QAAQ,UAAU,CACnC,IACF,EAAQ,MAAQ,GAOpB,iBAA4C,CAE1C,OADgB,KAAK,QAAQ,UAAU,EACvB,MAKlB,YAAqB,CACnB,OAAO,OAAO,YAAY"}
|
package/dist/elysia-plugin.cjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e=require(`./_virtual/rolldown_runtime.cjs`),t=require(`./context.cjs`),n=require(`./logger.cjs`);require(`elysia`);function r(e={}){let{logger:r=new n.Logger,logRequests:i=!0,logResponses:a=!0,excludePaths:o=[`/health`,`/metrics`]}=e,s=t.LogContext.getInstance();return function(e){return e.derive(e=>{let{request:t,path:n}=e;if(o.some(e=>n.startsWith(e)))return{logger:r};let a=new URL(t.url),c={requestId:s.generateId(),method:t.method,url:t.url,path:a.pathname,userAgent:t.headers.get(`user-agent`)||void 0,timestamp:new Date().toISOString()},l=performance.now();return s.run(c,()=>{i&&r.info(`→ ${t.method} ${n}`,{method:t.method,path:n,userAgent:c.userAgent,requestId:c.requestId})}),{logger:r,requestContext:c,startTime:l}}).onAfterHandle(e=>{let{request:t,startTime:n,requestContext:r,logger:i}=e;if(!n||!r)return;let o=performance.now()-n,s=new URL(t.url).pathname;a&&i.info(`← 200 ${t.method} ${s}`,{method:t.method,path:s,duration:`${o.toFixed(2)}ms`,requestId:r.requestId})}).onError(e=>{let{request:t,error:n,code:r,startTime:i,requestContext:a,logger:o}=e;if(!i||!a)return;let s=performance.now()-i,c=new URL(t.url).pathname;o?.error(`✖ ${r} ${t.method} ${c}`,{method:t.method,path:c,error:n?.toString?.()||`Unknown error`,code:r,duration:`${s.toFixed(2)}ms`,requestId:a.requestId})}).derive(()=>({logInfo:(e,t)=>{r.info(e,t)},logError:(e,t,n)=>{r.error(e,n,t)},traceOperation:async(e,t)=>r.trace({operationType:`custom`,operationName:e,autoTiming:!0},t)}))}}const i=r;exports.createElysiaLogger=i,exports.elysiaLogger=r;
|
package/dist/elysia-plugin.d.ts
DELETED
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import { ContextData } from "./types.js";
|
|
2
|
-
import { Logger } from "./logger.js";
|
|
3
|
-
import * as elysia0 from "elysia";
|
|
4
|
-
import { Elysia } from "elysia";
|
|
5
|
-
|
|
6
|
-
//#region src/elysia-plugin.d.ts
|
|
7
|
-
interface ElysiaLoggerConfig {
|
|
8
|
-
logger?: Logger;
|
|
9
|
-
logRequests?: boolean;
|
|
10
|
-
logResponses?: boolean;
|
|
11
|
-
excludePaths?: string[];
|
|
12
|
-
}
|
|
13
|
-
/**
|
|
14
|
-
* Simple ElysiaJS Logger Plugin
|
|
15
|
-
* Provides automatic request logging and tracing
|
|
16
|
-
*/
|
|
17
|
-
declare function elysiaLogger<T extends Elysia>(config?: ElysiaLoggerConfig): (app: T) => Elysia<"", {
|
|
18
|
-
decorator: {};
|
|
19
|
-
store: {};
|
|
20
|
-
derive: {};
|
|
21
|
-
resolve: {};
|
|
22
|
-
}, {
|
|
23
|
-
typebox: {};
|
|
24
|
-
error: {};
|
|
25
|
-
}, {
|
|
26
|
-
schema: {};
|
|
27
|
-
standaloneSchema: {};
|
|
28
|
-
macro: {};
|
|
29
|
-
macroFn: {};
|
|
30
|
-
parser: {};
|
|
31
|
-
response: {};
|
|
32
|
-
}, {}, {
|
|
33
|
-
derive: {};
|
|
34
|
-
resolve: {};
|
|
35
|
-
schema: {};
|
|
36
|
-
standaloneSchema: {};
|
|
37
|
-
response: {};
|
|
38
|
-
}, {
|
|
39
|
-
derive: ({
|
|
40
|
-
readonly logger: Logger;
|
|
41
|
-
readonly requestContext?: undefined;
|
|
42
|
-
readonly startTime?: undefined;
|
|
43
|
-
} | {
|
|
44
|
-
readonly logger: Logger;
|
|
45
|
-
readonly requestContext: ContextData;
|
|
46
|
-
readonly startTime: number;
|
|
47
|
-
}) & {
|
|
48
|
-
readonly logInfo: (message: string, metadata?: Record<string, any>) => void;
|
|
49
|
-
readonly logError: (message: string, error?: Error, metadata?: Record<string, any>) => void;
|
|
50
|
-
readonly traceOperation: <T_1>(operationName: string, operation: () => T_1 | Promise<T_1>) => Promise<T_1>;
|
|
51
|
-
};
|
|
52
|
-
resolve: {};
|
|
53
|
-
schema: {};
|
|
54
|
-
standaloneSchema: {};
|
|
55
|
-
response: elysia0.ExtractErrorFromHandle<{
|
|
56
|
-
readonly logInfo: (message: string, metadata?: Record<string, any>) => void;
|
|
57
|
-
readonly logError: (message: string, error?: Error, metadata?: Record<string, any>) => void;
|
|
58
|
-
readonly traceOperation: <T_1>(operationName: string, operation: () => T_1 | Promise<T_1>) => Promise<T_1>;
|
|
59
|
-
}>;
|
|
60
|
-
}>;
|
|
61
|
-
declare const createElysiaLogger: typeof elysiaLogger;
|
|
62
|
-
//#endregion
|
|
63
|
-
export { ElysiaLoggerConfig, createElysiaLogger, elysiaLogger };
|
|
64
|
-
//# sourceMappingURL=elysia-plugin.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"elysia-plugin.d.ts","names":[],"sources":["../src/elysia-plugin.ts"],"sourcesContent":[],"mappings":";;;;;;UAKiB,kBAAA;WACN;;EADM,YAAA,CAAA,EAAA,OAAkB;EAWnB,YAAA,CAAA,EAAY,MAAA,EAAA;;;;;;iBAAZ,uBAAuB,iBAC7B,2BAYc,MAAC;EA+EqB,SAAA,EAAA,CAAA,CAAA;EAK5B,KAAA,EAAA,CAAA,CAAA;EAEG,MAAA,EAAA,CAAA,CAAA;EAMM,OAAA,EAAA,CAAA,CAAA;CAAY,EAAA;EAAR,OAAA,EAAA,CAAA,CAAA;EACZ,KAAA,EAAA,CAAA,CAAA;CAAR,EAAA;EAdmC,MAAA,EAAA,CAAA,CAAA;EAK5B,gBAAA,EAAA,CAAA,CAAA;EAEG,KAAA,EAAA,CAAA,CAAA;EAMM,OAAA,EAAA,CAAA,CAAA;EAAY,MAAA,EAAA,CAAA,CAAA;EAAR,QAAA,EAAA,CAAA,CAAA;CACZ,EAAA,CAAA,CAAA,EAAA;EAAR,MAAA,EAAA,CAAA,CAAA;EAAO,OAAA,EAAA,CAAA,CAAA;EA7FO,MAAA,EAAA,CAAA,CAAA;EAAA,gBAAA,EAAA,CAAA,CAAA;EA4GZ,QAAA,EAAA,CAAA,CAAA;;;;;;;;;;;mDA7BiC;iDAK5B,kBAEG;2EAMM,MAAI,QAAQ,SAC5B,QAAQ;;;;;YAAD,OAAA,CAAA;mDAd4B;iDAK5B,kBAEG;2EAMM,MAAI,QAAQ,SAC5B,QAAQ;;;cAeN,2BAAkB"}
|
package/dist/elysia-plugin.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{LogContext as e}from"./context.js";import{Logger as t}from"./logger.js";import{Elysia as n}from"elysia";function r(n={}){let{logger:r=new t,logRequests:i=!0,logResponses:a=!0,excludePaths:o=[`/health`,`/metrics`]}=n,s=e.getInstance();return function(e){return e.derive(e=>{let{request:t,path:n}=e;if(o.some(e=>n.startsWith(e)))return{logger:r};let a=new URL(t.url),c={requestId:s.generateId(),method:t.method,url:t.url,path:a.pathname,userAgent:t.headers.get(`user-agent`)||void 0,timestamp:new Date().toISOString()},l=performance.now();return s.run(c,()=>{i&&r.info(`→ ${t.method} ${n}`,{method:t.method,path:n,userAgent:c.userAgent,requestId:c.requestId})}),{logger:r,requestContext:c,startTime:l}}).onAfterHandle(e=>{let{request:t,startTime:n,requestContext:r,logger:i}=e;if(!n||!r)return;let o=performance.now()-n,s=new URL(t.url).pathname;a&&i.info(`← 200 ${t.method} ${s}`,{method:t.method,path:s,duration:`${o.toFixed(2)}ms`,requestId:r.requestId})}).onError(e=>{let{request:t,error:n,code:r,startTime:i,requestContext:a,logger:o}=e;if(!i||!a)return;let s=performance.now()-i,c=new URL(t.url).pathname;o?.error(`✖ ${r} ${t.method} ${c}`,{method:t.method,path:c,error:n?.toString?.()||`Unknown error`,code:r,duration:`${s.toFixed(2)}ms`,requestId:a.requestId})}).derive(()=>({logInfo:(e,t)=>{r.info(e,t)},logError:(e,t,n)=>{r.error(e,n,t)},traceOperation:async(e,t)=>r.trace({operationType:`custom`,operationName:e,autoTiming:!0},t)}))}}const i=r;export{i as createElysiaLogger,r as elysiaLogger};
|
|
2
|
-
//# sourceMappingURL=elysia-plugin.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"elysia-plugin.js","names":["requestContext: ContextData"],"sources":["../src/elysia-plugin.ts"],"sourcesContent":["import { Logger } from './logger';\nimport { LogContext } from './context';\nimport type { ContextData } from './types';\nimport { Elysia } from 'elysia';\n\nexport interface ElysiaLoggerConfig {\n logger?: Logger;\n logRequests?: boolean;\n logResponses?: boolean;\n excludePaths?: string[];\n}\n\n/**\n * Simple ElysiaJS Logger Plugin\n * Provides automatic request logging and tracing\n */\nexport function elysiaLogger<T extends Elysia>(\n config: ElysiaLoggerConfig = {}\n) {\n const {\n logger = new Logger(),\n logRequests = true,\n logResponses = true,\n excludePaths = ['/health', '/metrics'],\n } = config;\n\n const context = LogContext.getInstance();\n\n // For type compatibility, we use a factory function\n return function (app: T) {\n return app\n .derive((ctx) => {\n const { request, path } = ctx;\n\n // Skip excluded paths\n if (excludePaths.some((excludePath) => path.startsWith(excludePath))) {\n return { logger };\n }\n\n // Create request context\n const url = new URL(request.url);\n const requestContext: ContextData = {\n requestId: context.generateId(),\n method: request.method,\n url: request.url,\n path: url.pathname,\n userAgent: request.headers.get('user-agent') || undefined,\n timestamp: new Date().toISOString(),\n };\n\n const startTime = performance.now();\n\n // Run in context\n context.run(requestContext, () => {\n // Log request\n if (logRequests) {\n logger.info(`→ ${request.method} ${path}`, {\n method: request.method,\n path,\n userAgent: requestContext.userAgent,\n requestId: requestContext.requestId,\n });\n }\n });\n\n return {\n logger,\n requestContext,\n startTime,\n };\n })\n .onAfterHandle((ctx) => {\n const { request, startTime, requestContext, logger } = ctx;\n\n if (!startTime || !requestContext) return;\n\n const duration = performance.now() - startTime;\n const path = new URL(request.url).pathname;\n\n if (logResponses) {\n logger.info(`← 200 ${request.method} ${path}`, {\n method: request.method,\n path,\n duration: `${duration.toFixed(2)}ms`,\n requestId: requestContext.requestId,\n });\n }\n })\n .onError((ctx) => {\n const { request, error, code, startTime, requestContext, logger } = ctx;\n\n if (!startTime || !requestContext) return;\n\n const duration = performance.now() - startTime;\n const path = new URL(request.url).pathname;\n\n logger?.error(`✖ ${code} ${request.method} ${path}`, {\n method: request.method,\n path,\n error: error?.toString?.() || 'Unknown error',\n code,\n duration: `${duration.toFixed(2)}ms`,\n requestId: requestContext.requestId,\n });\n })\n .derive(() => ({\n // Helper functions available in route handlers\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n logInfo: (message: string, metadata?: Record<string, any>) => {\n logger.info(message, metadata);\n },\n logError: (\n message: string,\n error?: Error,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata?: Record<string, any>\n ) => {\n logger.error(message, metadata, error);\n },\n traceOperation: async <T>(\n operationName: string,\n operation: () => T | Promise<T>\n ): Promise<T> => {\n return logger.trace(\n {\n operationType: 'custom',\n operationName,\n autoTiming: true,\n },\n operation\n );\n },\n }));\n };\n}\n\n// Export convenience functions\nexport const createElysiaLogger = elysiaLogger;\n"],"mappings":"+GAgBA,SAAgB,EACd,EAA6B,EAAE,CAC/B,CACA,GAAM,CACJ,SAAS,IAAI,EACb,cAAc,GACd,eAAe,GACf,eAAe,CAAC,UAAW,WAAW,EACpC,EAEE,EAAU,EAAW,aAAa,CAGxC,OAAO,SAAU,EAAQ,CACvB,OAAO,EACJ,OAAQ,GAAQ,CACf,GAAM,CAAE,UAAS,QAAS,EAG1B,GAAI,EAAa,KAAM,GAAgB,EAAK,WAAW,EAAY,CAAC,CAClE,MAAO,CAAE,SAAQ,CAInB,IAAM,EAAM,I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IAAmC,CAC5D,EAAO,KAAK,EAAS,EAAS,EAEhC,UACE,EACA,EAEA,IACG,CACH,EAAO,MAAM,EAAS,EAAU,EAAM,EAExC,eAAgB,MACd,EACA,IAEO,EAAO,MACZ,CACE,cAAe,SACf,gBACA,WAAY,GACb,CACD,EACD,CAEJ,EAAE,EAKT,MAAa,EAAqB"}
|
package/dist/formatters.cjs
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
const e=require(`./types.cjs`),t={reset:`\x1B[0m`,bright:`\x1B[1m`,dim:`\x1B[2m`,red:`\x1B[31m`,green:`\x1B[32m`,yellow:`\x1B[33m`,blue:`\x1B[34m`,magenta:`\x1B[35m`,cyan:`\x1B[36m`,white:`\x1B[37m`,gray:`\x1B[90m`,bgRed:`\x1B[41m`,bgYellow:`\x1B[43m`},n={[e.LogLevel.TRACE]:{color:t.gray,symbol:`○`,name:`TRACE`},[e.LogLevel.DEBUG]:{color:t.blue,symbol:`●`,name:`DEBUG`},[e.LogLevel.INFO]:{color:t.green,symbol:`●`,name:`INFO `},[e.LogLevel.WARN]:{color:t.yellow,symbol:`▲`,name:`WARN `},[e.LogLevel.ERROR]:{color:t.red,symbol:`✖`,name:`ERROR`},[e.LogLevel.FATAL]:{color:t.bgRed+t.white,symbol:`💀`,name:`FATAL`}};var r=class{enableColors;constructor(e=!0){this.enableColors=e}format(e){let r=[],i=n[e.level],a=this.formatTimestamp(e.timestamp);r.push(this.colorize(a,t.gray));let o=`${i.symbol} ${i.name}`;if(r.push(this.colorize(o,i.color)),e.traceId){let n=this.formatTraceInfo(e);r.push(this.colorize(n,t.cyan))}if(r.push(this.colorize(e.message,t.white)),e.duration!==void 0){let n=`(${this.formatDuration(e.duration)})`;r.push(this.colorize(n,t.magenta))}let s=r.join(` `);if(e.context&&Object.keys(e.context).length>0&&(s+=`
|
|
2
|
-
`+this.formatContext(e.context)),e.metadata&&Object.keys(e.metadata).length>0&&(s+=`
|
|
3
|
-
`+this.formatMetadata(e.metadata)),e.error&&(s+=`
|
|
4
|
-
`+this.formatError(e.error)),e.tags&&e.tags.length>0){let n=e.tags.map(e=>`#${e}`).join(` `);s+=`
|
|
5
|
-
`+this.colorize(`Tags: ${n}`,t.blue)}return s}formatTimestamp(e){return e.toISOString().substring(11,23)}formatTraceInfo(e){let t=[`trace:${e.traceId?.substring(0,8)||`unknown`}`];return e.spanId&&e.spanId.length>=8&&t.push(`span:${e.spanId.substring(0,8)}`),e.parentId&&e.parentId.length>=8&&t.push(`parent:${e.parentId.substring(0,8)}`),`[${t.join(`|`)}]`}formatDuration(e){return e<1?`${(e*1e3).toFixed(0)}μs`:e<1e3?`${e.toFixed(2)}ms`:`${(e/1e3).toFixed(2)}s`}formatContext(e){let n=this.formatObject(e,2);return this.colorize(`Context: ${n}`,t.cyan)}formatMetadata(e){let n=this.formatObject(e,2);return this.colorize(`Metadata: ${n}`,t.blue)}formatError(e){let n=this.colorize(`Error: ${e.name}: ${e.message}`,t.red);if(e.stack){let r=e.stack.split(`
|
|
6
|
-
`).slice(1,6).map(e=>` ${e}`).join(`
|
|
7
|
-
`);n+=`
|
|
8
|
-
`+this.colorize(r,t.gray)}return n}formatObject(e,t=0){let n=` `.repeat(t),r=Object.entries(e);return r.length===0?`{}`:r[0]&&typeof r[0][1]!=`object`?`{ ${r[0][0]}: ${this.formatValue(r[0][1])} }`:`{\n${r.map(([e,r])=>`${n} ${e}: ${this.formatValue(r,t+2)}`).join(`
|
|
9
|
-
`)}\n${n}}`}formatValue(e,t=0){return e===null?`null`:e===void 0?`undefined`:typeof e==`string`?`"${e}"`:typeof e==`boolean`||typeof e==`number`?String(e):e instanceof Date?e.toISOString():Array.isArray(e)?e.length===0?`[]`:`[${e.map(e=>this.formatValue(e)).join(`, `)}]`:typeof e==`object`?this.formatObject(e,t):String(e)}colorize(e,n){return this.enableColors?`${n}${e}${t.reset}`:e}},i=class{format(e){let t={timestamp:e.timestamp,level:e.level,message:e.message};return e.traceId&&(t.traceId=e.traceId),e.spanId&&(t.spanId=e.spanId),e.parentId&&(t.parentId=e.parentId),e.duration!==void 0&&(t.duration=e.duration),e.context&&Object.keys(e.context).length>0&&(t.context=e.context),e.metadata&&Object.keys(e.metadata).length>0&&(t.metadata=e.metadata),e.error&&(t.error={name:e.error.name,message:e.error.message,stack:e.error.stack}),e.tags&&e.tags.length>0&&(t.tags=e.tags),JSON.stringify(t)}},a=class{template;dateFormat;constructor(e=`{timestamp} [{level}] {message}`,t){this.template=e,this.dateFormat=t||(e=>e.toISOString())}format(t){let n=e.LogLevel[t.level],r=this.dateFormat(t.timestamp),i=this.template.replace(`{timestamp}`,r).replace(`{level}`,n).replace(`{message}`,t.message).replace(`{traceId}`,t.traceId||``).replace(`{spanId}`,t.spanId||``).replace(`{duration}`,t.duration?.toString()||``);return t.context&&(i=i.replace(`{context}`,JSON.stringify(t.context))),t.metadata&&(i=i.replace(`{metadata}`,JSON.stringify(t.metadata))),i}};exports.CustomFormatter=a,exports.DevFormatter=r,exports.ProductionFormatter=i;
|
package/dist/formatters.d.ts
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import { Formatter, LogEntry } from "./types.js";
|
|
2
|
-
|
|
3
|
-
//#region src/formatters.d.ts
|
|
4
|
-
declare class DevFormatter implements Formatter {
|
|
5
|
-
private enableColors;
|
|
6
|
-
constructor(enableColors?: boolean);
|
|
7
|
-
format(entry: LogEntry): string;
|
|
8
|
-
private formatTimestamp;
|
|
9
|
-
private formatTraceInfo;
|
|
10
|
-
private formatDuration;
|
|
11
|
-
private formatContext;
|
|
12
|
-
private formatMetadata;
|
|
13
|
-
private formatError;
|
|
14
|
-
private formatObject;
|
|
15
|
-
private formatValue;
|
|
16
|
-
private colorize;
|
|
17
|
-
}
|
|
18
|
-
declare class ProductionFormatter implements Formatter {
|
|
19
|
-
format(entry: LogEntry): string;
|
|
20
|
-
}
|
|
21
|
-
declare class CustomFormatter implements Formatter {
|
|
22
|
-
private template;
|
|
23
|
-
private dateFormat;
|
|
24
|
-
constructor(template?: string, dateFormat?: (date: Date) => string);
|
|
25
|
-
format(entry: LogEntry): string;
|
|
26
|
-
}
|
|
27
|
-
//#endregion
|
|
28
|
-
export { CustomFormatter, DevFormatter, ProductionFormatter };
|
|
29
|
-
//# sourceMappingURL=formatters.d.ts.map
|
package/dist/formatters.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"formatters.d.ts","names":[],"sources":["../src/formatters.ts"],"sourcesContent":[],"mappings":";;;cAkCa,YAAA,YAAwB;;EAAxB,WAAA,CAAA,YAOG,CAPU,EAOV,OAAA;EAkJH,MAAA,CAAA,KAAA,EAlJG,QAkJiB,CAAA,EAAA,MAAA;EAkDpB,QAAA,eAAgB;EAML,QAAA,eAAA;EAMR,QAAA,cAAA;EAZwB,QAAA,aAAA;EAAS,QAAA,cAAA;;;;;;cAlDpC,mBAAA,YAA+B;gBAC5B;;cAiDH,eAAA,YAA2B;;;qDAMhB;gBAMR"}
|
package/dist/formatters.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"formatters.js","names":["parts: string[]","logObject: LogEntry"],"sources":["../src/formatters.ts"],"sourcesContent":["import type { Formatter, LogEntry } from './types';\nimport { LogLevel } from './types';\n\n// ANSI color codes for terminal output\nconst colors = {\n reset: '\\x1b[0m',\n bright: '\\x1b[1m',\n dim: '\\x1b[2m',\n red: '\\x1b[31m',\n green: '\\x1b[32m',\n yellow: '\\x1b[33m',\n blue: '\\x1b[34m',\n magenta: '\\x1b[35m',\n cyan: '\\x1b[36m',\n white: '\\x1b[37m',\n gray: '\\x1b[90m',\n bgRed: '\\x1b[41m',\n bgYellow: '\\x1b[43m',\n};\n\n// Log level colors and symbols\nconst levelConfig = {\n [LogLevel.TRACE]: { color: colors.gray, symbol: '○', name: 'TRACE' },\n [LogLevel.DEBUG]: { color: colors.blue, symbol: '●', name: 'DEBUG' },\n [LogLevel.INFO]: { color: colors.green, symbol: '●', name: 'INFO ' },\n [LogLevel.WARN]: { color: colors.yellow, symbol: '▲', name: 'WARN ' },\n [LogLevel.ERROR]: { color: colors.red, symbol: '✖', name: 'ERROR' },\n [LogLevel.FATAL]: {\n color: colors.bgRed + colors.white,\n symbol: '💀',\n name: 'FATAL',\n },\n};\n\nexport class DevFormatter implements Formatter {\n private enableColors: boolean;\n\n constructor(enableColors = true) {\n this.enableColors = enableColors;\n }\n\n format(entry: LogEntry): string {\n const parts: string[] = [];\n const config = levelConfig[entry.level];\n\n // Timestamp\n const timestamp = this.formatTimestamp(entry.timestamp);\n parts.push(this.colorize(timestamp, colors.gray));\n\n // Log level with symbol\n const levelText = `${config.symbol} ${config.name}`;\n parts.push(this.colorize(levelText, config.color));\n\n // Trace information\n if (entry.traceId) {\n const traceInfo = this.formatTraceInfo(entry);\n parts.push(this.colorize(traceInfo, colors.cyan));\n }\n\n // Main message\n parts.push(this.colorize(entry.message, colors.white));\n\n // Duration (if present)\n if (entry.duration !== undefined) {\n const durationText = `(${this.formatDuration(entry.duration)})`;\n parts.push(this.colorize(durationText, colors.magenta));\n }\n\n let output = parts.join(' ');\n\n // Context and metadata (on new lines for readability)\n if (entry.context && Object.keys(entry.context).length > 0) {\n output += '\\n' + this.formatContext(entry.context);\n }\n\n if (entry.metadata && Object.keys(entry.metadata).length > 0) {\n output += '\\n' + this.formatMetadata(entry.metadata);\n }\n\n // Error details\n if (entry.error) {\n output += '\\n' + this.formatError(entry.error);\n }\n\n // Tags\n if (entry.tags && entry.tags.length > 0) {\n const tagsText = entry.tags.map((tag) => `#${tag}`).join(' ');\n output += '\\n' + this.colorize(`Tags: ${tagsText}`, colors.blue);\n }\n\n return output;\n }\n\n private formatTimestamp(timestamp: Date): string {\n return timestamp.toISOString().substring(11, 23); // Just time with milliseconds\n }\n\n private formatTraceInfo(entry: LogEntry): string {\n const parts = [`trace:${entry.traceId?.substring(0, 8) || 'unknown'}`];\n if (entry.spanId && entry.spanId.length >= 8) {\n parts.push(`span:${entry.spanId.substring(0, 8)}`);\n }\n if (entry.parentId && entry.parentId.length >= 8) {\n parts.push(`parent:${entry.parentId.substring(0, 8)}`);\n }\n return `[${parts.join('|')}]`;\n }\n\n private formatDuration(duration: number): string {\n if (duration < 1) {\n return `${(duration * 1000).toFixed(0)}μs`;\n } else if (duration < 1000) {\n return `${duration.toFixed(2)}ms`;\n } else {\n return `${(duration / 1000).toFixed(2)}s`;\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private formatContext(context: Record<string, any>): string {\n const formatted = this.formatObject(context, 2);\n return this.colorize(`Context: ${formatted}`, colors.cyan);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private formatMetadata(metadata: Record<string, any>): string {\n const formatted = this.formatObject(metadata, 2);\n return this.colorize(`Metadata: ${formatted}`, colors.blue);\n }\n\n private formatError(error: Error): string {\n let output = this.colorize(\n `Error: ${error.name}: ${error.message}`,\n colors.red\n );\n if (error.stack) {\n const stackLines = error.stack.split('\\n').slice(1, 6); // First 5 stack frames\n const indentedStack = stackLines.map((line) => ` ${line}`).join('\\n');\n output += '\\n' + this.colorize(indentedStack, colors.gray);\n }\n return output;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private formatObject(obj: Record<string, any>, indent = 0): string {\n const spaces = ' '.repeat(indent);\n const entries = Object.entries(obj);\n\n if (entries.length === 0) return '{}';\n\n if (entries[0] && typeof entries[0][1] !== 'object') {\n return `{ ${entries[0][0]}: ${this.formatValue(entries[0][1])} }`;\n }\n\n const formatted = entries\n .map(([key, value]) => {\n return `${spaces} ${key}: ${this.formatValue(value, indent + 2)}`;\n })\n .join('\\n');\n\n return `{\\n${formatted}\\n${spaces}}`;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private formatValue(value: any, indent = 0): string {\n if (value === null) return 'null';\n if (value === undefined) return 'undefined';\n if (typeof value === 'string') return `\"${value}\"`;\n if (typeof value === 'boolean' || typeof value === 'number')\n return String(value);\n if (value instanceof Date) return value.toISOString();\n if (Array.isArray(value)) {\n if (value.length === 0) return '[]';\n return `[${value.map((v) => this.formatValue(v)).join(', ')}]`;\n }\n if (typeof value === 'object') {\n return this.formatObject(value, indent);\n }\n return String(value);\n }\n\n private colorize(text: string, color: string): string {\n if (!this.enableColors) return text;\n return `${color}${text}${colors.reset}`;\n }\n}\n\nexport class ProductionFormatter implements Formatter {\n format(entry: LogEntry): string {\n const logObject: LogEntry = {\n timestamp: entry.timestamp,\n level: entry.level,\n message: entry.message,\n };\n\n // Add trace information\n if (entry.traceId) {\n logObject.traceId = entry.traceId;\n }\n if (entry.spanId) {\n logObject.spanId = entry.spanId;\n }\n if (entry.parentId) {\n logObject.parentId = entry.parentId;\n }\n\n // Add timing information\n if (entry.duration !== undefined) {\n logObject.duration = entry.duration;\n }\n\n // Add context and metadata\n if (entry.context && Object.keys(entry.context).length > 0) {\n logObject.context = entry.context;\n }\n if (entry.metadata && Object.keys(entry.metadata).length > 0) {\n logObject.metadata = entry.metadata;\n }\n\n // Add error information\n if (entry.error) {\n logObject.error = {\n name: entry.error.name,\n message: entry.error.message,\n stack: entry.error.stack,\n };\n }\n\n // Add tags\n if (entry.tags && entry.tags.length > 0) {\n logObject.tags = entry.tags;\n }\n\n return JSON.stringify(logObject);\n }\n}\n\nexport class CustomFormatter implements Formatter {\n private template: string;\n private dateFormat: (date: Date) => string;\n\n constructor(\n template = '{timestamp} [{level}] {message}',\n dateFormat?: (date: Date) => string\n ) {\n this.template = template;\n this.dateFormat = dateFormat || ((date: Date) => date.toISOString());\n }\n\n format(entry: LogEntry): string {\n const levelName = LogLevel[entry.level];\n const timestamp = this.dateFormat(entry.timestamp);\n\n let formatted = this.template\n .replace('{timestamp}', timestamp)\n .replace('{level}', levelName)\n .replace('{message}', entry.message)\n .replace('{traceId}', entry.traceId || '')\n .replace('{spanId}', entry.spanId || '')\n .replace('{duration}', entry.duration?.toString() || '');\n\n // Handle context and metadata placeholders\n if (entry.context) {\n formatted = formatted.replace('{context}', JSON.stringify(entry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CAa1D,OAVI,EAAM,UACR,EAAY,EAAU,QAAQ,YAAa,KAAK,UAAU,EAAM,QAAQ,CAAC,EAEvE,EAAM,WACR,EAAY,EAAU,QACpB,aACA,KAAK,UAAU,EAAM,SAAS,CAC/B,EAGI"}
|
package/dist/index.cjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e=require(`./context.cjs`),t=require(`./types.cjs`),n=require(`./timer.cjs`),r=require(`./tracer.cjs`),i=require(`./formatters.cjs`),a=require(`./logger.cjs`),o=require(`./elysia-plugin.cjs`);exports.DevFormatter=i.DevFormatter,exports.LogContext=e.LogContext,exports.LogLevel=t.LogLevel,exports.Logger=a.Logger,exports.ProductionFormatter=i.ProductionFormatter,exports.Timer=n.Timer,exports.Tracer=r.Tracer,exports.createElysiaLogger=o.createElysiaLogger,exports.elysiaLogger=o.elysiaLogger;
|