@murky-web/simplelog 2.0.1 → 3.1.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 +151 -16
- package/dist/browser_console.js +91 -0
- package/dist/browser_console.js.map +1 -0
- package/dist/{deno_logger.d.ts → browser_logger.d.ts} +1 -3
- package/dist/browser_logger.d.ts.map +1 -0
- package/dist/browser_logger.js +17 -0
- package/dist/browser_logger.js.map +1 -0
- package/dist/bun_logger.d.ts +0 -2
- package/dist/bun_logger.d.ts.map +1 -1
- package/dist/bun_logger.js +1 -2
- package/dist/bun_logger.js.map +1 -1
- package/dist/console_defaults.js +45 -0
- package/dist/console_defaults.js.map +1 -0
- package/dist/console_text.d.ts +25 -0
- package/dist/console_text.d.ts.map +1 -0
- package/dist/console_text.js +168 -0
- package/dist/console_text.js.map +1 -0
- package/dist/console_timestamp.d.ts +4 -0
- package/dist/console_timestamp.d.ts.map +1 -0
- package/dist/console_timestamp.js +22 -0
- package/dist/console_timestamp.js.map +1 -0
- package/dist/hono_middleware.d.ts +14 -4
- package/dist/hono_middleware.d.ts.map +1 -1
- package/dist/hono_middleware.js +45 -20
- package/dist/hono_middleware.js.map +1 -1
- package/dist/log_file.d.ts +9 -0
- package/dist/log_file.d.ts.map +1 -0
- package/dist/log_file.js +52 -0
- package/dist/log_file.js.map +1 -0
- package/dist/logger.d.ts +0 -2
- package/dist/logger.d.ts.map +1 -1
- package/dist/logger.js +1 -2
- package/dist/logger.js.map +1 -1
- package/dist/logger_factory.d.ts +45 -11
- package/dist/logger_factory.d.ts.map +1 -1
- package/dist/logger_factory.js +38 -217
- package/dist/logger_factory.js.map +1 -1
- package/dist/node_runtime.js +17 -6
- package/dist/node_runtime.js.map +1 -1
- package/dist/otel.d.ts +0 -2
- package/dist/otel.d.ts.map +1 -1
- package/dist/otel.js +2 -3
- package/dist/serialize_value.d.ts +44 -0
- package/dist/serialize_value.d.ts.map +1 -0
- package/dist/serialize_value.js +313 -0
- package/dist/serialize_value.js.map +1 -0
- package/dist/web_logger.d.ts +0 -2
- package/dist/web_logger.d.ts.map +1 -1
- package/dist/web_logger.js +3 -3
- package/dist/web_logger.js.map +1 -1
- package/oxlint/prefer-runtime-entry.mjs +1 -1
- package/package.json +19 -13
- package/dist/deno_logger.d.ts.map +0 -1
- package/dist/deno_logger.js +0 -39
- package/dist/deno_logger.js.map +0 -1
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { formatConsoleTimestamp } from "./console_timestamp.js";
|
|
2
|
+
import { buildLogMessage, formatOpenTelemetryContextLabel } from "./logger_factory.js";
|
|
3
|
+
import { formatFunctionLabel, toJsonSafeValue } from "./serialize_value.js";
|
|
4
|
+
// src/console_text.ts
|
|
5
|
+
const ANSI_RESET_COLOR = 0;
|
|
6
|
+
const ANSI_GREEN = 32;
|
|
7
|
+
const ANSI_YELLOW = 33;
|
|
8
|
+
const ANSI_RED = 31;
|
|
9
|
+
const ANSI_CYAN = 36;
|
|
10
|
+
const ANSI_BLUE = 34;
|
|
11
|
+
const ANSI_MAGENTA = 35;
|
|
12
|
+
const ANSI_GRAY = 90;
|
|
13
|
+
const EMPTY_LENGTH = 0;
|
|
14
|
+
const JSON_INDENTATION = 2;
|
|
15
|
+
const FALLBACK_OBJECT_STRING = "[Object]";
|
|
16
|
+
const LOG_LEVEL_COLORS = {
|
|
17
|
+
DEBUG: ANSI_CYAN,
|
|
18
|
+
ERROR: ANSI_RED,
|
|
19
|
+
INFO: ANSI_GREEN,
|
|
20
|
+
WARN: ANSI_YELLOW
|
|
21
|
+
};
|
|
22
|
+
function colorize(text, colorCode) {
|
|
23
|
+
return `\u001B[${colorCode}m${text}\u001B[${ANSI_RESET_COLOR}m`;
|
|
24
|
+
}
|
|
25
|
+
function isPrimitiveArgument(argument) {
|
|
26
|
+
return typeof argument === "bigint" || typeof argument === "boolean" || typeof argument === "number" || typeof argument === "string" || typeof argument === "symbol";
|
|
27
|
+
}
|
|
28
|
+
function stringifyPrimitiveArgument(argument) {
|
|
29
|
+
if (typeof argument === "string") return {
|
|
30
|
+
kind: "string",
|
|
31
|
+
text: argument
|
|
32
|
+
};
|
|
33
|
+
if (typeof argument === "symbol") return {
|
|
34
|
+
kind: "symbol",
|
|
35
|
+
text: argument.toString()
|
|
36
|
+
};
|
|
37
|
+
if (typeof argument === "boolean") return {
|
|
38
|
+
kind: "boolean",
|
|
39
|
+
text: `${argument}`
|
|
40
|
+
};
|
|
41
|
+
return {
|
|
42
|
+
kind: "number",
|
|
43
|
+
text: `${argument}`
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
function stringifyFunctionArgument(functionName) {
|
|
47
|
+
return {
|
|
48
|
+
kind: "function",
|
|
49
|
+
text: formatFunctionLabel(functionName)
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function stringifyJsonArgument(argument) {
|
|
53
|
+
try {
|
|
54
|
+
const safeValue = toJsonSafeValue(argument);
|
|
55
|
+
const stringifiedArgument = JSON.stringify(safeValue, void 0, JSON_INDENTATION);
|
|
56
|
+
if (typeof stringifiedArgument !== "string") return {
|
|
57
|
+
kind: "object",
|
|
58
|
+
text: FALLBACK_OBJECT_STRING
|
|
59
|
+
};
|
|
60
|
+
return {
|
|
61
|
+
jsonValue: safeValue,
|
|
62
|
+
kind: "object",
|
|
63
|
+
text: stringifiedArgument
|
|
64
|
+
};
|
|
65
|
+
} catch {
|
|
66
|
+
return {
|
|
67
|
+
kind: "object",
|
|
68
|
+
text: FALLBACK_OBJECT_STRING
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function stringifyArgument(argument) {
|
|
73
|
+
if (typeof argument === "undefined") return {
|
|
74
|
+
kind: "nullish",
|
|
75
|
+
text: "undefined"
|
|
76
|
+
};
|
|
77
|
+
if (argument === null) return {
|
|
78
|
+
kind: "nullish",
|
|
79
|
+
text: "null"
|
|
80
|
+
};
|
|
81
|
+
if (isPrimitiveArgument(argument)) return stringifyPrimitiveArgument(argument);
|
|
82
|
+
if (typeof argument === "function") return stringifyFunctionArgument(argument.name);
|
|
83
|
+
return stringifyJsonArgument(argument);
|
|
84
|
+
}
|
|
85
|
+
function stringifyArguments(argumentsList) {
|
|
86
|
+
return argumentsList.map((argument) => {
|
|
87
|
+
return stringifyArgument(argument);
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
function buildColoredLogMessage(level, timestamp, loggerName, openTelemetryContextLabel, message) {
|
|
91
|
+
const colorCode = LOG_LEVEL_COLORS[level];
|
|
92
|
+
return buildLogMessage(colorize(timestamp, colorCode), colorize(`[${level}]`, colorCode), colorize(loggerName, colorCode), openTelemetryContextLabel, colorize(message, colorCode));
|
|
93
|
+
}
|
|
94
|
+
function colorizeOpenTelemetryContextLabel(level, openTelemetryContext, valueColorMode) {
|
|
95
|
+
const plainOpenTelemetryContextLabel = formatOpenTelemetryContextLabel(openTelemetryContext);
|
|
96
|
+
if (valueColorMode === "off" || plainOpenTelemetryContextLabel.length === EMPTY_LENGTH) return plainOpenTelemetryContextLabel;
|
|
97
|
+
if (valueColorMode === "syntax") return colorize(plainOpenTelemetryContextLabel, ANSI_GRAY);
|
|
98
|
+
return colorize(plainOpenTelemetryContextLabel, LOG_LEVEL_COLORS[level]);
|
|
99
|
+
}
|
|
100
|
+
function getSyntaxColorCode(kind) {
|
|
101
|
+
switch (kind) {
|
|
102
|
+
case "boolean": return ANSI_YELLOW;
|
|
103
|
+
case "function": return ANSI_MAGENTA;
|
|
104
|
+
case "nullish": return ANSI_GRAY;
|
|
105
|
+
case "number": return ANSI_CYAN;
|
|
106
|
+
case "object": return ANSI_BLUE;
|
|
107
|
+
case "string": return ANSI_GREEN;
|
|
108
|
+
case "symbol": return ANSI_MAGENTA;
|
|
109
|
+
default: return ANSI_GREEN;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function colorizeArguments(argumentsList, level, valueColorMode) {
|
|
113
|
+
if (valueColorMode === "off") return argumentsList.map((argument) => {
|
|
114
|
+
return argument.text;
|
|
115
|
+
});
|
|
116
|
+
if (valueColorMode === "syntax") return argumentsList.map((argument) => {
|
|
117
|
+
return colorize(argument.text, getSyntaxColorCode(argument.kind));
|
|
118
|
+
});
|
|
119
|
+
const colorCode = LOG_LEVEL_COLORS[level];
|
|
120
|
+
return argumentsList.map((argument) => {
|
|
121
|
+
return colorize(argument.text, colorCode);
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
function buildPlainConsoleLogMessage(level, timestamp, loggerName, openTelemetryContext, message) {
|
|
125
|
+
return buildLogMessage(timestamp, `[${level}]`, loggerName, formatOpenTelemetryContextLabel(openTelemetryContext), message);
|
|
126
|
+
}
|
|
127
|
+
function buildConsoleLogMessage(level, timestamp, loggerName, openTelemetryContext, message, valueColorMode) {
|
|
128
|
+
if (valueColorMode === "off") return buildPlainConsoleLogMessage(level, timestamp, loggerName, openTelemetryContext, message);
|
|
129
|
+
return buildColoredLogMessage(level, timestamp, loggerName, colorizeOpenTelemetryContextLabel(level, openTelemetryContext, valueColorMode), message);
|
|
130
|
+
}
|
|
131
|
+
function buildConsoleStackTrace(stackTrace, level, valueColorMode) {
|
|
132
|
+
if (valueColorMode === "off") return stackTrace;
|
|
133
|
+
return colorize(stackTrace, LOG_LEVEL_COLORS[level]);
|
|
134
|
+
}
|
|
135
|
+
function createConsolePayload(entry, args, output) {
|
|
136
|
+
const { level } = entry;
|
|
137
|
+
const { valueColorMode } = output;
|
|
138
|
+
return {
|
|
139
|
+
consoleArgs: colorizeArguments(args, level, valueColorMode),
|
|
140
|
+
consoleLogMessage: buildConsoleLogMessage(level, formatConsoleTimestamp(entry.epochMilliseconds, output.timestampFormat), entry.loggerName, entry.openTelemetryContext, entry.message, valueColorMode),
|
|
141
|
+
consoleStackTrace: buildConsoleStackTrace(entry.stackTrace, level, valueColorMode)
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* The writer for terminals and server logs: every argument is turned into text
|
|
146
|
+
* (objects as JSON, with the safety rules of `toJsonSafeValue`), colored with
|
|
147
|
+
* ANSI codes unless `valueColorMode` is `"off"`.
|
|
148
|
+
*
|
|
149
|
+
* @param {LoggerConsole} loggerConsole - Where console output goes.
|
|
150
|
+
* @param {LogFileWriter} [writeLogFile] - Writes the log file; only runtimes
|
|
151
|
+
* that can write files pass one.
|
|
152
|
+
* @returns {LogWriter} The runtime's `write`.
|
|
153
|
+
*/
|
|
154
|
+
function createTextLogWriter(loggerConsole, writeLogFile) {
|
|
155
|
+
return (entry, output) => {
|
|
156
|
+
const args = stringifyArguments(entry.args);
|
|
157
|
+
if (output.writeToFile && typeof writeLogFile === "function") writeLogFile(output.logFilePath, {
|
|
158
|
+
...entry,
|
|
159
|
+
args
|
|
160
|
+
});
|
|
161
|
+
const payload = createConsolePayload(entry, args, output);
|
|
162
|
+
loggerConsole.log(payload.consoleLogMessage, ...payload.consoleArgs);
|
|
163
|
+
if (entry.stackTrace.length > EMPTY_LENGTH) loggerConsole.error(payload.consoleStackTrace);
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
export { createTextLogWriter };
|
|
167
|
+
|
|
168
|
+
//# sourceMappingURL=console_text.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"console_text.js","names":[],"sources":["../src/console_text.ts"],"sourcesContent":["import { formatConsoleTimestamp } from \"./console_timestamp\";\nimport type { LogFileWriter } from \"./log_file\";\nimport {\n buildLogMessage,\n formatOpenTelemetryContextLabel,\n} from \"./logger_factory\";\nimport type {\n LogEntry,\n LoggerConsole,\n LogLevel,\n LogOutput,\n LogWriter,\n OpenTelemetryContext,\n ValueColorMode,\n} from \"./logger_factory\";\nimport { formatFunctionLabel, toJsonSafeValue } from \"./serialize_value\";\n\nconst ANSI_RESET_COLOR = 0;\nconst ANSI_GREEN = 32;\nconst ANSI_YELLOW = 33;\nconst ANSI_RED = 31;\nconst ANSI_CYAN = 36;\nconst ANSI_BLUE = 34;\nconst ANSI_MAGENTA = 35;\nconst ANSI_GRAY = 90;\nconst EMPTY_LENGTH = 0;\nconst JSON_INDENTATION = 2;\nconst FALLBACK_OBJECT_STRING = \"[Object]\";\n\ntype ConsolePayload = Readonly<{\n consoleArgs: readonly string[];\n consoleLogMessage: string;\n consoleStackTrace: string;\n}>;\n\ntype StringifiablePrimitive = bigint | boolean | number | string | symbol;\n\ntype StringifiedArgument = Readonly<{\n /**\n * The JSON-safe value behind an object's `text`. The log file writes it as\n * compact JSON; it is only serialized again when a file is written.\n */\n jsonValue?: unknown;\n kind: StringifiedArgumentKind;\n text: string;\n}>;\n\ntype StringifiedArgumentKind =\n | \"boolean\"\n | \"function\"\n | \"nullish\"\n | \"number\"\n | \"object\"\n | \"string\"\n | \"symbol\";\n\nconst LOG_LEVEL_COLORS: Readonly<Record<LogLevel, number>> = {\n DEBUG: ANSI_CYAN,\n ERROR: ANSI_RED,\n INFO: ANSI_GREEN,\n WARN: ANSI_YELLOW,\n};\n\nfunction colorize(text: string, colorCode: number): string {\n return `\\u001B[${colorCode}m${text}\\u001B[${ANSI_RESET_COLOR}m`;\n}\n\nfunction isPrimitiveArgument(\n argument: unknown,\n): argument is StringifiablePrimitive {\n return (\n typeof argument === \"bigint\" ||\n typeof argument === \"boolean\" ||\n typeof argument === \"number\" ||\n typeof argument === \"string\" ||\n typeof argument === \"symbol\"\n );\n}\n\nfunction stringifyPrimitiveArgument(\n argument: StringifiablePrimitive,\n): StringifiedArgument {\n if (typeof argument === \"string\") {\n return {\n kind: \"string\",\n text: argument,\n };\n }\n\n if (typeof argument === \"symbol\") {\n return {\n kind: \"symbol\",\n text: argument.toString(),\n };\n }\n\n if (typeof argument === \"boolean\") {\n return {\n kind: \"boolean\",\n text: `${argument}`,\n };\n }\n\n return {\n kind: \"number\",\n text: `${argument}`,\n };\n}\n\nfunction stringifyFunctionArgument(functionName: string): StringifiedArgument {\n return {\n kind: \"function\",\n text: formatFunctionLabel(functionName),\n };\n}\n\nfunction stringifyJsonArgument(argument: unknown): StringifiedArgument {\n try {\n const safeValue = toJsonSafeValue(argument);\n const stringifiedArgument = JSON.stringify(\n safeValue,\n undefined,\n JSON_INDENTATION,\n );\n\n if (typeof stringifiedArgument !== \"string\") {\n return {\n kind: \"object\",\n text: FALLBACK_OBJECT_STRING,\n };\n }\n\n return {\n jsonValue: safeValue,\n kind: \"object\",\n text: stringifiedArgument,\n };\n } catch {\n return {\n kind: \"object\",\n text: FALLBACK_OBJECT_STRING,\n };\n }\n}\n\nfunction stringifyArgument(argument: unknown): StringifiedArgument {\n if (typeof argument === \"undefined\") {\n return {\n kind: \"nullish\",\n text: \"undefined\",\n };\n }\n\n if (argument === null) {\n return {\n kind: \"nullish\",\n text: \"null\",\n };\n }\n\n if (isPrimitiveArgument(argument)) {\n return stringifyPrimitiveArgument(argument);\n }\n\n if (typeof argument === \"function\") {\n return stringifyFunctionArgument(argument.name);\n }\n\n return stringifyJsonArgument(argument);\n}\n\nfunction stringifyArguments(\n argumentsList: readonly unknown[],\n): readonly StringifiedArgument[] {\n return argumentsList.map((argument) => {\n return stringifyArgument(argument);\n });\n}\n\nfunction buildColoredLogMessage(\n level: LogLevel,\n timestamp: string,\n loggerName: string,\n openTelemetryContextLabel: string,\n message: string,\n): string {\n const colorCode = LOG_LEVEL_COLORS[level];\n\n return buildLogMessage(\n colorize(timestamp, colorCode),\n colorize(`[${level}]`, colorCode),\n colorize(loggerName, colorCode),\n openTelemetryContextLabel,\n colorize(message, colorCode),\n );\n}\n\nfunction colorizeOpenTelemetryContextLabel(\n level: LogLevel,\n openTelemetryContext: OpenTelemetryContext | undefined,\n valueColorMode: ValueColorMode,\n): string {\n const plainOpenTelemetryContextLabel =\n formatOpenTelemetryContextLabel(openTelemetryContext);\n\n if (\n valueColorMode === \"off\" ||\n plainOpenTelemetryContextLabel.length === EMPTY_LENGTH\n ) {\n return plainOpenTelemetryContextLabel;\n }\n\n if (valueColorMode === \"syntax\") {\n return colorize(plainOpenTelemetryContextLabel, ANSI_GRAY);\n }\n\n return colorize(plainOpenTelemetryContextLabel, LOG_LEVEL_COLORS[level]);\n}\n\nfunction getSyntaxColorCode(kind: StringifiedArgumentKind): number {\n switch (kind) {\n case \"boolean\": {\n return ANSI_YELLOW;\n }\n case \"function\": {\n return ANSI_MAGENTA;\n }\n case \"nullish\": {\n return ANSI_GRAY;\n }\n case \"number\": {\n return ANSI_CYAN;\n }\n case \"object\": {\n return ANSI_BLUE;\n }\n case \"string\": {\n return ANSI_GREEN;\n }\n case \"symbol\": {\n return ANSI_MAGENTA;\n }\n default: {\n return ANSI_GREEN;\n }\n }\n}\n\nfunction colorizeArguments(\n argumentsList: readonly StringifiedArgument[],\n level: LogLevel,\n valueColorMode: ValueColorMode,\n): readonly string[] {\n if (valueColorMode === \"off\") {\n return argumentsList.map((argument) => {\n return argument.text;\n });\n }\n\n if (valueColorMode === \"syntax\") {\n return argumentsList.map((argument) => {\n return colorize(argument.text, getSyntaxColorCode(argument.kind));\n });\n }\n\n const colorCode = LOG_LEVEL_COLORS[level];\n\n return argumentsList.map((argument) => {\n return colorize(argument.text, colorCode);\n });\n}\n\nfunction buildPlainConsoleLogMessage(\n level: LogLevel,\n timestamp: string,\n loggerName: string,\n openTelemetryContext: OpenTelemetryContext | undefined,\n message: string,\n): string {\n return buildLogMessage(\n timestamp,\n `[${level}]`,\n loggerName,\n formatOpenTelemetryContextLabel(openTelemetryContext),\n message,\n );\n}\n\nfunction buildConsoleLogMessage(\n level: LogLevel,\n timestamp: string,\n loggerName: string,\n openTelemetryContext: OpenTelemetryContext | undefined,\n message: string,\n valueColorMode: ValueColorMode,\n): string {\n if (valueColorMode === \"off\") {\n return buildPlainConsoleLogMessage(\n level,\n timestamp,\n loggerName,\n openTelemetryContext,\n message,\n );\n }\n\n return buildColoredLogMessage(\n level,\n timestamp,\n loggerName,\n colorizeOpenTelemetryContextLabel(\n level,\n openTelemetryContext,\n valueColorMode,\n ),\n message,\n );\n}\n\nfunction buildConsoleStackTrace(\n stackTrace: string,\n level: LogLevel,\n valueColorMode: ValueColorMode,\n): string {\n if (valueColorMode === \"off\") {\n return stackTrace;\n }\n\n return colorize(stackTrace, LOG_LEVEL_COLORS[level]);\n}\n\nfunction createConsolePayload(\n entry: LogEntry,\n args: readonly StringifiedArgument[],\n output: LogOutput,\n): ConsolePayload {\n const { level } = entry;\n const { valueColorMode } = output;\n\n return {\n consoleArgs: colorizeArguments(args, level, valueColorMode),\n consoleLogMessage: buildConsoleLogMessage(\n level,\n formatConsoleTimestamp(\n entry.epochMilliseconds,\n output.timestampFormat,\n ),\n entry.loggerName,\n entry.openTelemetryContext,\n entry.message,\n valueColorMode,\n ),\n consoleStackTrace: buildConsoleStackTrace(\n entry.stackTrace,\n level,\n valueColorMode,\n ),\n };\n}\n\n/**\n * The writer for terminals and server logs: every argument is turned into text\n * (objects as JSON, with the safety rules of `toJsonSafeValue`), colored with\n * ANSI codes unless `valueColorMode` is `\"off\"`.\n *\n * @param {LoggerConsole} loggerConsole - Where console output goes.\n * @param {LogFileWriter} [writeLogFile] - Writes the log file; only runtimes\n * that can write files pass one.\n * @returns {LogWriter} The runtime's `write`.\n */\nfunction createTextLogWriter(\n loggerConsole: LoggerConsole,\n writeLogFile?: LogFileWriter,\n): LogWriter {\n return (entry, output) => {\n const args = stringifyArguments(entry.args);\n\n if (output.writeToFile && typeof writeLogFile === \"function\") {\n writeLogFile(output.logFilePath, { ...entry, args });\n }\n\n const payload = createConsolePayload(entry, args, output);\n\n loggerConsole.log(payload.consoleLogMessage, ...payload.consoleArgs);\n if (entry.stackTrace.length > EMPTY_LENGTH) {\n loggerConsole.error(payload.consoleStackTrace);\n }\n };\n}\n\nexport { createTextLogWriter };\nexport type { StringifiedArgument };\n"],"mappings":";;;;AAiBA,MAAM,mBAAmB;AACzB,MAAM,aAAa;AACnB,MAAM,cAAc;AACpB,MAAM,WAAW;AACjB,MAAM,YAAY;AAClB,MAAM,YAAY;AAClB,MAAM,eAAe;AACrB,MAAM,YAAY;AAClB,MAAM,eAAe;AACrB,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SACM;CACN,OAAO,gBACH,WACA,IAAI,MAAM,IACV,YACA,gCAAgC,oBAAoB,GACpD,OACJ;AACJ;AAEA,SAAS,uBACL,OACA,WACA,YACA,sBACA,SACA,gBACM;CACN,IAAI,mBAAmB,OACnB,OAAO,4BACH,OACA,WACA,YACA,sBACA,OACJ;CAGJ,OAAO,uBACH,OACA,WACA,YACA,kCACI,OACA,sBACA,cACJ,GACA,OACJ;AACJ;AAEA,SAAS,uBACL,YACA,OACA,gBACM;CACN,IAAI,mBAAmB,OACnB,OAAO;CAGX,OAAO,SAAS,YAAY,iBAAiB,MAAM;AACvD;AAEA,SAAS,qBACL,OACA,MACA,QACc;CACd,MAAM,EAAE,UAAU;CAClB,MAAM,EAAE,mBAAmB;CAE3B,OAAO;EACH,aAAa,kBAAkB,MAAM,OAAO,cAAc;EAC1D,mBAAmB,uBACf,OACA,uBACI,MAAM,mBACN,OAAO,eACX,GACA,MAAM,YACN,MAAM,sBACN,MAAM,SACN,cACJ;EACA,mBAAmB,uBACf,MAAM,YACN,OACA,cACJ;CACJ;AACJ;;;;;;;;;;;AAYA,SAAS,oBACL,eACA,cACS;CACT,QAAQ,OAAO,WAAW;EACtB,MAAM,OAAO,mBAAmB,MAAM,IAAI;EAE1C,IAAI,OAAO,eAAe,OAAO,iBAAiB,YAC9C,aAAa,OAAO,aAAa;GAAE,GAAG;GAAO;EAAK,CAAC;EAGvD,MAAM,UAAU,qBAAqB,OAAO,MAAM,MAAM;EAExD,cAAc,IAAI,QAAQ,mBAAmB,GAAG,QAAQ,WAAW;EACnE,IAAI,MAAM,WAAW,SAAS,cAC1B,cAAc,MAAM,QAAQ,iBAAiB;CAErD;AACJ"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"console_timestamp.d.ts","names":[],"sources":["../src/console_timestamp.ts"],"mappings":";KACK"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// src/console_timestamp.ts
|
|
2
|
+
const TIME_PART_WIDTH = 2;
|
|
3
|
+
const MILLISECONDS_WIDTH = 3;
|
|
4
|
+
function padTimePart(value, width = TIME_PART_WIDTH) {
|
|
5
|
+
return `${value}`.padStart(width, "0");
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* `"time"` is the local time of day, the clock a developer reads the log
|
|
9
|
+
* against.
|
|
10
|
+
*
|
|
11
|
+
* @param {number} epochMilliseconds - The moment of the log call.
|
|
12
|
+
* @param {TimestampFormat} format - The console timestamp format.
|
|
13
|
+
* @returns {string} `16:59:23.745` for `"time"`, the ISO string for `"iso"`.
|
|
14
|
+
*/
|
|
15
|
+
function formatConsoleTimestamp(epochMilliseconds, format) {
|
|
16
|
+
const date = new Date(epochMilliseconds);
|
|
17
|
+
if (format === "iso") return date.toISOString();
|
|
18
|
+
return `${padTimePart(date.getHours())}:${padTimePart(date.getMinutes())}:${padTimePart(date.getSeconds())}.${padTimePart(date.getMilliseconds(), MILLISECONDS_WIDTH)}`;
|
|
19
|
+
}
|
|
20
|
+
export { formatConsoleTimestamp };
|
|
21
|
+
|
|
22
|
+
//# sourceMappingURL=console_timestamp.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"console_timestamp.js","names":[],"sources":["../src/console_timestamp.ts"],"sourcesContent":["/** `\"iso\"`: `2026-11-19T16:59:23.745Z`; `\"time\"`: local `16:59:23.745`. */\ntype TimestampFormat = \"iso\" | \"time\";\n\nconst TIME_PART_WIDTH = 2;\nconst MILLISECONDS_WIDTH = 3;\n\nfunction padTimePart(value: number, width = TIME_PART_WIDTH): string {\n return `${value}`.padStart(width, \"0\");\n}\n\n/**\n * `\"time\"` is the local time of day, the clock a developer reads the log\n * against.\n *\n * @param {number} epochMilliseconds - The moment of the log call.\n * @param {TimestampFormat} format - The console timestamp format.\n * @returns {string} `16:59:23.745` for `\"time\"`, the ISO string for `\"iso\"`.\n */\nfunction formatConsoleTimestamp(\n epochMilliseconds: number,\n format: TimestampFormat,\n): string {\n const date = new Date(epochMilliseconds);\n\n if (format === \"iso\") {\n return date.toISOString();\n }\n\n return `${padTimePart(date.getHours())}:${padTimePart(date.getMinutes())}:${padTimePart(date.getSeconds())}.${padTimePart(date.getMilliseconds(), MILLISECONDS_WIDTH)}`;\n}\n\nexport { formatConsoleTimestamp };\nexport type { TimestampFormat };\n"],"mappings":";AAGA,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAE3B,SAAS,YAAY,OAAe,QAAQ,iBAAyB;CACjE,OAAO,GAAG,QAAQ,SAAS,OAAO,GAAG;AACzC;;;;;;;;;AAUA,SAAS,uBACL,mBACA,QACM;CACN,MAAM,OAAO,IAAI,KAAK,iBAAiB;CAEvC,IAAI,WAAW,OACX,OAAO,KAAK,YAAY;CAG5B,OAAO,GAAG,YAAY,KAAK,SAAS,CAAC,EAAE,GAAG,YAAY,KAAK,WAAW,CAAC,EAAE,GAAG,YAAY,KAAK,WAAW,CAAC,EAAE,GAAG,YAAY,KAAK,gBAAgB,GAAG,kBAAkB;AACxK"}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { LoggerBase } from "./logger_factory.js";
|
|
2
|
-
import { getRuntimeKey } from "hono/adapter";
|
|
3
1
|
import { MiddlewareHandler } from "hono";
|
|
4
|
-
|
|
2
|
+
import { getRuntimeKey } from "hono/adapter";
|
|
3
|
+
import { LoggerBase } from "./logger_factory.js";
|
|
5
4
|
type RequestRuntimeKey = ReturnType<typeof getRuntimeKey>;
|
|
6
5
|
type HonoLoggerVariables = {
|
|
7
6
|
logger: LoggerBase;
|
|
@@ -12,17 +11,28 @@ type HonoLoggerMiddleware = MiddlewareHandler<{
|
|
|
12
11
|
type RequestLoggerContext = Readonly<{
|
|
13
12
|
method: string;
|
|
14
13
|
path: string;
|
|
14
|
+
/**
|
|
15
|
+
* The query string including the leading `?` (`"?a=1&b=2"`), or `""` when
|
|
16
|
+
* there is none. It is passed to `requestLoggerName` only; the middleware
|
|
17
|
+
* logs it as `query` just when `includeQuery` is on.
|
|
18
|
+
*/
|
|
19
|
+
query: string;
|
|
15
20
|
requestId: string;
|
|
16
21
|
runtime: RequestRuntimeKey;
|
|
17
22
|
url: string;
|
|
18
23
|
}>;
|
|
19
24
|
type RequestLoggerNameResolver = (context: RequestLoggerContext) => string;
|
|
20
25
|
type HonoLoggerMiddlewareOptions = Readonly<{
|
|
26
|
+
/**
|
|
27
|
+
* Adds the request's query string (`?a=1&b=2`) to the logged metadata as
|
|
28
|
+
* `query`. Off by default: query strings often carry tokens, OAuth codes and
|
|
29
|
+
* e-mail addresses, and the log keeps only the path.
|
|
30
|
+
*/
|
|
31
|
+
includeQuery?: boolean;
|
|
21
32
|
logCompletedRequests?: boolean;
|
|
22
33
|
logger: Readonly<LoggerBase>;
|
|
23
34
|
requestLoggerName?: RequestLoggerNameResolver | string;
|
|
24
35
|
}>;
|
|
25
36
|
declare function createHonoLoggerMiddleware(options: HonoLoggerMiddlewareOptions): HonoLoggerMiddleware;
|
|
26
|
-
//#endregion
|
|
27
37
|
export { type HonoLoggerMiddlewareOptions, type HonoLoggerVariables, type RequestLoggerContext, createHonoLoggerMiddleware };
|
|
28
38
|
//# sourceMappingURL=hono_middleware.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hono_middleware.d.ts","names":[],"sources":["../src/hono_middleware.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"hono_middleware.d.ts","names":[],"sources":["../src/hono_middleware.ts"],"mappings":";;;KAcK,oBAAoB,kBAAkB;KAEtC;EACD,QAAQ;;KAGP,uBAAuB;EACxB,WAAW;;KAmCV,uBAAuB;EACxB;EACA;;;;;;EAMA;EACA;EACA,SAAS;EACT;;KAGC,6BAA6B,SAAS;KAEtC,8BAA8B;;;;;;EAM/B;EACA;EACA,QAAQ,SAAS;EACjB,oBAAoB;;iBA0Pf,2BACL,SAAS,8BACV"}
|
package/dist/hono_middleware.js
CHANGED
|
@@ -1,21 +1,30 @@
|
|
|
1
1
|
import { getRuntimeKey } from "hono/adapter";
|
|
2
2
|
import { createMiddleware } from "hono/factory";
|
|
3
|
-
|
|
3
|
+
// src/hono_middleware.ts
|
|
4
4
|
const DEFAULT_ERROR_STATUS = 500;
|
|
5
5
|
const DEFAULT_REQUEST_LOGGER_NAME = "request";
|
|
6
6
|
const EMPTY_REQUEST_ID = "";
|
|
7
7
|
const FAILED_REQUEST_MESSAGE = "Request failed";
|
|
8
8
|
const REQUEST_COMPLETED_MESSAGE = "Request completed";
|
|
9
9
|
const REQUEST_ID_HEADER = "x-request-id";
|
|
10
|
+
const EMPTY_QUERY = "";
|
|
10
11
|
function resolveRequestId(c) {
|
|
11
12
|
const requestId = c.req.header(REQUEST_ID_HEADER);
|
|
12
13
|
if (typeof requestId !== "string" || requestId.length === 0) return EMPTY_REQUEST_ID;
|
|
13
14
|
return requestId;
|
|
14
15
|
}
|
|
16
|
+
function extractQuery(url) {
|
|
17
|
+
try {
|
|
18
|
+
return new URL(url).search;
|
|
19
|
+
} catch {
|
|
20
|
+
return EMPTY_QUERY;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
15
23
|
function createRequestLoggerContext(c) {
|
|
16
24
|
return {
|
|
17
25
|
method: c.req.method,
|
|
18
26
|
path: c.req.path,
|
|
27
|
+
query: extractQuery(c.req.url),
|
|
19
28
|
requestId: resolveRequestId(c),
|
|
20
29
|
runtime: getRuntimeKey(),
|
|
21
30
|
url: c.req.url
|
|
@@ -29,37 +38,50 @@ function resolveRequestLoggerName(requestLoggerContext, requestLoggerName) {
|
|
|
29
38
|
function createRequestLogger(logger, requestLoggerContext, requestLoggerName) {
|
|
30
39
|
return logger.createChildLogger(resolveRequestLoggerName(requestLoggerContext, requestLoggerName));
|
|
31
40
|
}
|
|
41
|
+
function createRequestOnlyReader(c) {
|
|
42
|
+
return { req: {
|
|
43
|
+
header(name) {
|
|
44
|
+
return c.req.header(name);
|
|
45
|
+
},
|
|
46
|
+
method: c.req.method,
|
|
47
|
+
path: c.req.path,
|
|
48
|
+
url: c.req.url
|
|
49
|
+
} };
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Reads the response status, so call it only after `next()`. Hono's `c.res`
|
|
53
|
+
* getter creates a placeholder Response on first access, and a handler's own
|
|
54
|
+
* Response is then copied into a new one (`new Response(body, res)`) when it is
|
|
55
|
+
* set. Touching `c.res` before the handler ran therefore replaces every
|
|
56
|
+
* response and loses its identity.
|
|
57
|
+
*
|
|
58
|
+
* @param {MiddlewareContext} c - The Hono context, after `next()` returned.
|
|
59
|
+
* @returns {RequestContextReader} The request, the error and the status.
|
|
60
|
+
*/
|
|
32
61
|
function createRequestReader(c) {
|
|
33
62
|
return {
|
|
63
|
+
...createRequestOnlyReader(c),
|
|
34
64
|
error: c.error,
|
|
35
|
-
req: {
|
|
36
|
-
header(name) {
|
|
37
|
-
return c.req.header(name);
|
|
38
|
-
},
|
|
39
|
-
method: c.req.method,
|
|
40
|
-
path: c.req.path,
|
|
41
|
-
url: c.req.url
|
|
42
|
-
},
|
|
43
65
|
res: { status: c.res.status }
|
|
44
66
|
};
|
|
45
67
|
}
|
|
46
68
|
function createRequestLoggingState(c, options) {
|
|
47
|
-
const requestLoggerContext = createRequestLoggerContext(
|
|
69
|
+
const requestLoggerContext = createRequestLoggerContext(createRequestOnlyReader(c));
|
|
48
70
|
return {
|
|
49
71
|
requestLogger: createRequestLogger(options.logger, requestLoggerContext, options.requestLoggerName),
|
|
50
72
|
requestLoggerContext,
|
|
51
73
|
startTime: Date.now()
|
|
52
74
|
};
|
|
53
75
|
}
|
|
54
|
-
function buildRequestMetadata(requestLoggerContext, durationMs, status) {
|
|
76
|
+
function buildRequestMetadata(requestLoggerContext, includeQuery, durationMs, status) {
|
|
55
77
|
const requestMetadata = {
|
|
56
78
|
durationMs,
|
|
57
79
|
method: requestLoggerContext.method,
|
|
58
80
|
path: requestLoggerContext.path,
|
|
59
81
|
runtime: requestLoggerContext.runtime,
|
|
60
|
-
status
|
|
61
|
-
url: requestLoggerContext.url
|
|
82
|
+
status
|
|
62
83
|
};
|
|
84
|
+
if (includeQuery && requestLoggerContext.query.length > 0) requestMetadata.query = requestLoggerContext.query;
|
|
63
85
|
if (requestLoggerContext.requestId.length > 0) requestMetadata.requestId = requestLoggerContext.requestId;
|
|
64
86
|
return requestMetadata;
|
|
65
87
|
}
|
|
@@ -81,20 +103,24 @@ function getElapsedMilliseconds(startTime) {
|
|
|
81
103
|
function shouldLogCompletedRequests(logCompletedRequests) {
|
|
82
104
|
return logCompletedRequests ?? true;
|
|
83
105
|
}
|
|
84
|
-
function
|
|
85
|
-
|
|
106
|
+
function shouldIncludeQuery(includeQuery) {
|
|
107
|
+
return includeQuery ?? false;
|
|
108
|
+
}
|
|
109
|
+
function logCompletedRequest(c, requestLogger, requestLoggerContext, includeQuery, startTime) {
|
|
110
|
+
requestLogger.info(REQUEST_COMPLETED_MESSAGE, buildRequestMetadata(requestLoggerContext, includeQuery, getElapsedMilliseconds(startTime), c.res.status));
|
|
86
111
|
}
|
|
87
|
-
function logFailedRequest(c, requestLogger, requestLoggerContext, startTime) {
|
|
88
|
-
requestLogger.error(FAILED_REQUEST_MESSAGE, buildRequestMetadata(requestLoggerContext, getElapsedMilliseconds(startTime), c.res.status || DEFAULT_ERROR_STATUS), serializeThrownError(c.error));
|
|
112
|
+
function logFailedRequest(c, requestLogger, requestLoggerContext, includeQuery, startTime) {
|
|
113
|
+
requestLogger.error(FAILED_REQUEST_MESSAGE, buildRequestMetadata(requestLoggerContext, includeQuery, getElapsedMilliseconds(startTime), c.res.status || DEFAULT_ERROR_STATUS), serializeThrownError(c.error));
|
|
89
114
|
}
|
|
90
115
|
function finalizeRequestLogging(c, options, requestLoggingState) {
|
|
91
116
|
const requestReader = createRequestReader(c);
|
|
117
|
+
const includeQuery = shouldIncludeQuery(options.includeQuery);
|
|
92
118
|
if (typeof requestReader.error !== "undefined") {
|
|
93
|
-
logFailedRequest(requestReader, requestLoggingState.requestLogger, requestLoggingState.requestLoggerContext, requestLoggingState.startTime);
|
|
119
|
+
logFailedRequest(requestReader, requestLoggingState.requestLogger, requestLoggingState.requestLoggerContext, includeQuery, requestLoggingState.startTime);
|
|
94
120
|
return;
|
|
95
121
|
}
|
|
96
122
|
if (!shouldLogCompletedRequests(options.logCompletedRequests)) return;
|
|
97
|
-
logCompletedRequest(requestReader, requestLoggingState.requestLogger, requestLoggingState.requestLoggerContext, requestLoggingState.startTime);
|
|
123
|
+
logCompletedRequest(requestReader, requestLoggingState.requestLogger, requestLoggingState.requestLoggerContext, includeQuery, requestLoggingState.startTime);
|
|
98
124
|
}
|
|
99
125
|
function createHonoLoggerMiddleware(options) {
|
|
100
126
|
return createMiddleware(async (...[c, next]) => {
|
|
@@ -104,7 +130,6 @@ function createHonoLoggerMiddleware(options) {
|
|
|
104
130
|
finalizeRequestLogging(c, options, requestLoggingState);
|
|
105
131
|
});
|
|
106
132
|
}
|
|
107
|
-
//#endregion
|
|
108
133
|
export { createHonoLoggerMiddleware };
|
|
109
134
|
|
|
110
135
|
//# sourceMappingURL=hono_middleware.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hono_middleware.js","names":[],"sources":["../src/hono_middleware.ts"],"sourcesContent":["import { getRuntimeKey } from \"hono/adapter\";\nimport { createMiddleware } from \"hono/factory\";\nimport type { MiddlewareHandler } from \"hono\";\n\nimport type { LoggerBase } from \"./logger_factory\";\n\nconst DEFAULT_ERROR_STATUS = 500;\nconst DEFAULT_REQUEST_LOGGER_NAME = \"request\";\nconst EMPTY_REQUEST_ID = \"\";\nconst FAILED_REQUEST_MESSAGE = \"Request failed\";\nconst REQUEST_COMPLETED_MESSAGE = \"Request completed\";\nconst REQUEST_ID_HEADER = \"x-request-id\";\n\ntype RequestRuntimeKey = ReturnType<typeof getRuntimeKey>;\n\ntype HonoLoggerVariables = {\n logger: LoggerBase;\n};\n\ntype HonoLoggerMiddleware = MiddlewareHandler<{\n Variables: HonoLoggerVariables;\n}>;\n\ntype RequestLike = Readonly<{\n header: (name: string) => string | undefined;\n method: string;\n path: string;\n url: string;\n}>;\n\ntype ResponseLike = Readonly<{\n status: number;\n}>;\n\ntype RequestContextReader = Readonly<{\n error?: unknown;\n req: RequestLike;\n res: ResponseLike;\n}>;\n\ntype MiddlewareContext = Readonly<{\n error?: unknown;\n req: RequestLike;\n res: ResponseLike;\n set: (key: \"logger\", value: Readonly<LoggerBase>) => void;\n}>;\n\ntype MiddlewareParameters = readonly [MiddlewareContext, () => Promise<void>];\n\ntype RequestMetadataValue = number | string;\n\ntype RequestLoggerContext = Readonly<{\n method: string;\n path: string;\n requestId: string;\n runtime: RequestRuntimeKey;\n url: string;\n}>;\n\ntype RequestLoggerNameResolver = (context: RequestLoggerContext) => string;\n\ntype HonoLoggerMiddlewareOptions = Readonly<{\n logCompletedRequests?: boolean;\n logger: Readonly<LoggerBase>;\n requestLoggerName?: RequestLoggerNameResolver | string;\n}>;\n\ntype RequestLoggingState = Readonly<{\n requestLogger: Readonly<LoggerBase>;\n requestLoggerContext: RequestLoggerContext;\n startTime: number;\n}>;\n\nfunction resolveRequestId(c: RequestContextReader): string {\n const requestId = c.req.header(REQUEST_ID_HEADER);\n\n if (typeof requestId !== \"string\" || requestId.length === EMPTY_REQUEST_ID.length) {\n return EMPTY_REQUEST_ID;\n }\n\n return requestId;\n}\n\nfunction createRequestLoggerContext(c: RequestContextReader): RequestLoggerContext {\n return {\n method: c.req.method,\n path: c.req.path,\n requestId: resolveRequestId(c),\n runtime: getRuntimeKey(),\n url: c.req.url,\n };\n}\n\nfunction resolveRequestLoggerName(\n requestLoggerContext: RequestLoggerContext,\n requestLoggerName: HonoLoggerMiddlewareOptions[\"requestLoggerName\"],\n): string {\n if (typeof requestLoggerName === \"function\") {\n return requestLoggerName(requestLoggerContext);\n }\n\n if (typeof requestLoggerName === \"string\") {\n return requestLoggerName;\n }\n\n return DEFAULT_REQUEST_LOGGER_NAME;\n}\n\nfunction createRequestLogger(\n logger: Readonly<LoggerBase>,\n requestLoggerContext: RequestLoggerContext,\n requestLoggerName: HonoLoggerMiddlewareOptions[\"requestLoggerName\"],\n): Readonly<LoggerBase> {\n return logger.createChildLogger(\n resolveRequestLoggerName(requestLoggerContext, requestLoggerName),\n );\n}\n\nfunction createRequestReader(c: MiddlewareContext): RequestContextReader {\n return {\n error: c.error,\n req: {\n header(name: string): string | undefined {\n return c.req.header(name);\n },\n method: c.req.method,\n path: c.req.path,\n url: c.req.url,\n },\n res: {\n status: c.res.status,\n },\n };\n}\n\nfunction createRequestLoggingState(\n c: MiddlewareContext,\n options: HonoLoggerMiddlewareOptions,\n): RequestLoggingState {\n const requestLoggerContext = createRequestLoggerContext(createRequestReader(c));\n\n return {\n requestLogger: createRequestLogger(\n options.logger,\n requestLoggerContext,\n options.requestLoggerName,\n ),\n requestLoggerContext,\n startTime: Date.now(),\n };\n}\n\nfunction buildRequestMetadata(\n requestLoggerContext: RequestLoggerContext,\n durationMs: number,\n status: number,\n): Readonly<Record<string, RequestMetadataValue>> {\n const requestMetadata: Record<string, RequestMetadataValue> = {\n durationMs,\n method: requestLoggerContext.method,\n path: requestLoggerContext.path,\n runtime: requestLoggerContext.runtime,\n status,\n url: requestLoggerContext.url,\n };\n\n if (requestLoggerContext.requestId.length > EMPTY_REQUEST_ID.length) {\n requestMetadata.requestId = requestLoggerContext.requestId;\n }\n\n return requestMetadata;\n}\n\nfunction serializeThrownError(error: unknown): Readonly<Record<string, string>> {\n if (error instanceof Error) {\n return {\n message: error.message,\n name: error.name,\n stack: error.stack ?? \"\",\n };\n }\n\n return {\n message: String(error),\n name: \"UnknownError\",\n stack: \"\",\n };\n}\n\nfunction getElapsedMilliseconds(startTime: number): number {\n return Date.now() - startTime;\n}\n\nfunction shouldLogCompletedRequests(\n logCompletedRequests: boolean | undefined,\n): boolean {\n return logCompletedRequests ?? true;\n}\n\nfunction logCompletedRequest(\n c: RequestContextReader,\n requestLogger: Readonly<LoggerBase>,\n requestLoggerContext: RequestLoggerContext,\n startTime: number,\n): void {\n requestLogger.info(\n REQUEST_COMPLETED_MESSAGE,\n buildRequestMetadata(\n requestLoggerContext,\n getElapsedMilliseconds(startTime),\n c.res.status,\n ),\n );\n}\n\nfunction logFailedRequest(\n c: RequestContextReader,\n requestLogger: Readonly<LoggerBase>,\n requestLoggerContext: RequestLoggerContext,\n startTime: number,\n): void {\n requestLogger.error(\n FAILED_REQUEST_MESSAGE,\n buildRequestMetadata(\n requestLoggerContext,\n getElapsedMilliseconds(startTime),\n c.res.status || DEFAULT_ERROR_STATUS,\n ),\n serializeThrownError(c.error),\n );\n}\n\nfunction finalizeRequestLogging(\n c: MiddlewareContext,\n options: HonoLoggerMiddlewareOptions,\n requestLoggingState: RequestLoggingState,\n): void {\n const requestReader = createRequestReader(c);\n\n if (typeof requestReader.error !== \"undefined\") {\n logFailedRequest(\n requestReader,\n requestLoggingState.requestLogger,\n requestLoggingState.requestLoggerContext,\n requestLoggingState.startTime,\n );\n return;\n }\n\n if (!shouldLogCompletedRequests(options.logCompletedRequests)) {\n return;\n }\n\n logCompletedRequest(\n requestReader,\n requestLoggingState.requestLogger,\n requestLoggingState.requestLoggerContext,\n requestLoggingState.startTime,\n );\n}\n\nfunction createHonoLoggerMiddleware(\n options: HonoLoggerMiddlewareOptions,\n): HonoLoggerMiddleware {\n return createMiddleware<{\n Variables: HonoLoggerVariables;\n }>(async (...[c, next]: MiddlewareParameters): Promise<void> => {\n const requestLoggingState = createRequestLoggingState(c, options);\n\n c.set(\"logger\", requestLoggingState.requestLogger);\n await next();\n finalizeRequestLogging(c, options, requestLoggingState);\n });\n}\n\nexport { createHonoLoggerMiddleware };\n\nexport type {\n HonoLoggerMiddlewareOptions,\n HonoLoggerVariables,\n RequestLoggerContext,\n};\n"],"mappings":";;;AAMA,MAAM,uBAAuB;AAC7B,MAAM,8BAA8B;AACpC,MAAM,mBAAmB;AACzB,MAAM,yBAAyB;AAC/B,MAAM,4BAA4B;AAClC,MAAM,oBAAoB;AA8D1B,SAAS,iBAAiB,GAAiC;CACzD,MAAM,YAAY,EA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,OAAO;EACL,SAAS,MAAM;EACf,MAAM,MAAM;EACZ,OAAO,MAAM,SAAS;CACxB;CAGF,OAAO;EACL,SAAS,OAAO,KAAK;EACrB,MAAM;EACN,OAAO;CACT;AACF;AAEA,SAAS,uBAAuB,WAA2B;CACzD,OAAO,KAAK,IAAI,IAAI;AACtB;AAEA,SAAS,2BACP,sBACS;CACT,OAAO,wBAAwB;AACjC;AAEA,SAAS,oBACP,GACA,eACA,sBACA,WACM;CACN,cAAc,KACZ,2BACA,qBACE,sBACA,uBAAuB,SAAS,GAChC,EAAE,IAAI,MACR,CACF;AACF;AAEA,SAAS,iBACP,GACA,eACA,sBACA,WACM;CACN,cAAc,MACZ,wBACA,qBACE,sBACA,uBAAuB,SAAS,GAChC,EAAE,IAAI,UAAU,oBAClB,GACA,qBAAqB,EAAE,KAAK,CAC9B;AACF;AAEA,SAAS,uBACP,GACA,SACA,qBACM;CACN,MAAM,gBAAgB,oBAAoB,CAAC;CAE3C,IAAI,OAAO,cAAc,UAAU,aAAa;EAC9C,iBACE,eACA,oBAAoB,eACpB,oBAAoB,sBACpB,oBAAoB,SACtB;EACA;CACF;CAEA,IAAI,CAAC,2BAA2B,QAAQ,oBAAoB,GAC1D;CAGF,oBACE,eACA,oBAAoB,eACpB,oBAAoB,sBACpB,oBAAoB,SACtB;AACF;AAEA,SAAS,2BACP,SACsB;CACtB,OAAO,iBAEJ,OAAO,GAAG,CAAC,GAAG,UAA+C;EAC9D,MAAM,sBAAsB,0BAA0B,GAAG,OAAO;EAEhE,EAAE,IAAI,UAAU,oBAAoB,aAAa;EACjD,MAAM,KAAK;EACX,uBAAuB,GAAG,SAAS,mBAAmB;CACxD,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"hono_middleware.js","names":[],"sources":["../src/hono_middleware.ts"],"sourcesContent":["import type { MiddlewareHandler } from \"hono\";\nimport { getRuntimeKey } from \"hono/adapter\";\nimport { createMiddleware } from \"hono/factory\";\n\nimport type { LoggerBase } from \"./logger_factory\";\n\nconst DEFAULT_ERROR_STATUS = 500;\nconst DEFAULT_REQUEST_LOGGER_NAME = \"request\";\nconst EMPTY_REQUEST_ID = \"\";\nconst FAILED_REQUEST_MESSAGE = \"Request failed\";\nconst REQUEST_COMPLETED_MESSAGE = \"Request completed\";\nconst REQUEST_ID_HEADER = \"x-request-id\";\nconst EMPTY_QUERY = \"\";\n\ntype RequestRuntimeKey = ReturnType<typeof getRuntimeKey>;\n\ntype HonoLoggerVariables = {\n logger: LoggerBase;\n};\n\ntype HonoLoggerMiddleware = MiddlewareHandler<{\n Variables: HonoLoggerVariables;\n}>;\n\ntype RequestLike = Readonly<{\n header: (name: string) => string | undefined;\n method: string;\n path: string;\n url: string;\n}>;\n\ntype ResponseLike = Readonly<{\n status: number;\n}>;\n\ntype RequestOnlyReader = Readonly<{\n req: RequestLike;\n}>;\n\ntype RequestContextReader = Readonly<{\n error?: unknown;\n req: RequestLike;\n res: ResponseLike;\n}>;\n\ntype MiddlewareContext = Readonly<{\n error?: unknown;\n req: RequestLike;\n res: ResponseLike;\n set: (key: \"logger\", value: Readonly<LoggerBase>) => void;\n}>;\n\ntype MiddlewareParameters = readonly [MiddlewareContext, () => Promise<void>];\n\ntype RequestMetadataValue = number | string;\n\ntype RequestLoggerContext = Readonly<{\n method: string;\n path: string;\n /**\n * The query string including the leading `?` (`\"?a=1&b=2\"`), or `\"\"` when\n * there is none. It is passed to `requestLoggerName` only; the middleware\n * logs it as `query` just when `includeQuery` is on.\n */\n query: string;\n requestId: string;\n runtime: RequestRuntimeKey;\n url: string;\n}>;\n\ntype RequestLoggerNameResolver = (context: RequestLoggerContext) => string;\n\ntype HonoLoggerMiddlewareOptions = Readonly<{\n /**\n * Adds the request's query string (`?a=1&b=2`) to the logged metadata as\n * `query`. Off by default: query strings often carry tokens, OAuth codes and\n * e-mail addresses, and the log keeps only the path.\n */\n includeQuery?: boolean;\n logCompletedRequests?: boolean;\n logger: Readonly<LoggerBase>;\n requestLoggerName?: RequestLoggerNameResolver | string;\n}>;\n\ntype RequestLoggingState = Readonly<{\n requestLogger: Readonly<LoggerBase>;\n requestLoggerContext: RequestLoggerContext;\n startTime: number;\n}>;\n\nfunction resolveRequestId(c: RequestOnlyReader): string {\n const requestId = c.req.header(REQUEST_ID_HEADER);\n\n if (\n typeof requestId !== \"string\" ||\n requestId.length === EMPTY_REQUEST_ID.length\n ) {\n return EMPTY_REQUEST_ID;\n }\n\n return requestId;\n}\n\nfunction extractQuery(url: string): string {\n try {\n return new URL(url).search;\n } catch {\n // Hono hands out absolute URLs; anything else has no query we can trust.\n return EMPTY_QUERY;\n }\n}\n\nfunction createRequestLoggerContext(\n c: RequestOnlyReader,\n): RequestLoggerContext {\n return {\n method: c.req.method,\n path: c.req.path,\n query: extractQuery(c.req.url),\n requestId: resolveRequestId(c),\n runtime: getRuntimeKey(),\n url: c.req.url,\n };\n}\n\nfunction resolveRequestLoggerName(\n requestLoggerContext: RequestLoggerContext,\n requestLoggerName: HonoLoggerMiddlewareOptions[\"requestLoggerName\"],\n): string {\n if (typeof requestLoggerName === \"function\") {\n return requestLoggerName(requestLoggerContext);\n }\n\n if (typeof requestLoggerName === \"string\") {\n return requestLoggerName;\n }\n\n return DEFAULT_REQUEST_LOGGER_NAME;\n}\n\nfunction createRequestLogger(\n logger: Readonly<LoggerBase>,\n requestLoggerContext: RequestLoggerContext,\n requestLoggerName: HonoLoggerMiddlewareOptions[\"requestLoggerName\"],\n): Readonly<LoggerBase> {\n return logger.createChildLogger(\n resolveRequestLoggerName(requestLoggerContext, requestLoggerName),\n );\n}\n\nfunction createRequestOnlyReader(c: MiddlewareContext): RequestOnlyReader {\n return {\n req: {\n header(name: string): string | undefined {\n return c.req.header(name);\n },\n method: c.req.method,\n path: c.req.path,\n url: c.req.url,\n },\n };\n}\n\n/**\n * Reads the response status, so call it only after `next()`. Hono's `c.res`\n * getter creates a placeholder Response on first access, and a handler's own\n * Response is then copied into a new one (`new Response(body, res)`) when it is\n * set. Touching `c.res` before the handler ran therefore replaces every\n * response and loses its identity.\n *\n * @param {MiddlewareContext} c - The Hono context, after `next()` returned.\n * @returns {RequestContextReader} The request, the error and the status.\n */\nfunction createRequestReader(c: MiddlewareContext): RequestContextReader {\n return {\n ...createRequestOnlyReader(c),\n error: c.error,\n res: {\n status: c.res.status,\n },\n };\n}\n\nfunction createRequestLoggingState(\n c: MiddlewareContext,\n options: HonoLoggerMiddlewareOptions,\n): RequestLoggingState {\n const requestLoggerContext = createRequestLoggerContext(\n createRequestOnlyReader(c),\n );\n\n return {\n requestLogger: createRequestLogger(\n options.logger,\n requestLoggerContext,\n options.requestLoggerName,\n ),\n requestLoggerContext,\n startTime: Date.now(),\n };\n}\n\nfunction buildRequestMetadata(\n requestLoggerContext: RequestLoggerContext,\n includeQuery: boolean,\n durationMs: number,\n status: number,\n): Readonly<Record<string, RequestMetadataValue>> {\n const requestMetadata: Record<string, RequestMetadataValue> = {\n durationMs,\n method: requestLoggerContext.method,\n path: requestLoggerContext.path,\n runtime: requestLoggerContext.runtime,\n status,\n };\n\n if (\n includeQuery &&\n requestLoggerContext.query.length > EMPTY_QUERY.length\n ) {\n requestMetadata.query = requestLoggerContext.query;\n }\n\n if (requestLoggerContext.requestId.length > EMPTY_REQUEST_ID.length) {\n requestMetadata.requestId = requestLoggerContext.requestId;\n }\n\n return requestMetadata;\n}\n\nfunction serializeThrownError(\n error: unknown,\n): Readonly<Record<string, string>> {\n if (error instanceof Error) {\n return {\n message: error.message,\n name: error.name,\n stack: error.stack ?? \"\",\n };\n }\n\n return {\n message: String(error),\n name: \"UnknownError\",\n stack: \"\",\n };\n}\n\nfunction getElapsedMilliseconds(startTime: number): number {\n return Date.now() - startTime;\n}\n\nfunction shouldLogCompletedRequests(\n logCompletedRequests: boolean | undefined,\n): boolean {\n return logCompletedRequests ?? true;\n}\n\nfunction shouldIncludeQuery(includeQuery: boolean | undefined): boolean {\n return includeQuery ?? false;\n}\n\nfunction logCompletedRequest(\n c: RequestContextReader,\n requestLogger: Readonly<LoggerBase>,\n requestLoggerContext: RequestLoggerContext,\n includeQuery: boolean,\n startTime: number,\n): void {\n requestLogger.info(\n REQUEST_COMPLETED_MESSAGE,\n buildRequestMetadata(\n requestLoggerContext,\n includeQuery,\n getElapsedMilliseconds(startTime),\n c.res.status,\n ),\n );\n}\n\nfunction logFailedRequest(\n c: RequestContextReader,\n requestLogger: Readonly<LoggerBase>,\n requestLoggerContext: RequestLoggerContext,\n includeQuery: boolean,\n startTime: number,\n): void {\n requestLogger.error(\n FAILED_REQUEST_MESSAGE,\n buildRequestMetadata(\n requestLoggerContext,\n includeQuery,\n getElapsedMilliseconds(startTime),\n c.res.status || DEFAULT_ERROR_STATUS,\n ),\n serializeThrownError(c.error),\n );\n}\n\nfunction finalizeRequestLogging(\n c: MiddlewareContext,\n options: HonoLoggerMiddlewareOptions,\n requestLoggingState: RequestLoggingState,\n): void {\n const requestReader = createRequestReader(c);\n const includeQuery = shouldIncludeQuery(options.includeQuery);\n\n if (typeof requestReader.error !== \"undefined\") {\n logFailedRequest(\n requestReader,\n requestLoggingState.requestLogger,\n requestLoggingState.requestLoggerContext,\n includeQuery,\n requestLoggingState.startTime,\n );\n return;\n }\n\n if (!shouldLogCompletedRequests(options.logCompletedRequests)) {\n return;\n }\n\n logCompletedRequest(\n requestReader,\n requestLoggingState.requestLogger,\n requestLoggingState.requestLoggerContext,\n includeQuery,\n requestLoggingState.startTime,\n );\n}\n\nfunction createHonoLoggerMiddleware(\n options: HonoLoggerMiddlewareOptions,\n): HonoLoggerMiddleware {\n return createMiddleware<{\n Variables: HonoLoggerVariables;\n }>(async (...[c, next]: MiddlewareParameters): Promise<void> => {\n const requestLoggingState = createRequestLoggingState(c, options);\n\n c.set(\"logger\", requestLoggingState.requestLogger);\n await next();\n finalizeRequestLogging(c, options, requestLoggingState);\n });\n}\n\nexport { createHonoLoggerMiddleware };\n\nexport type {\n HonoLoggerMiddlewareOptions,\n HonoLoggerVariables,\n RequestLoggerContext,\n};\n"],"mappings":";;;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UAAU,aAAa;EAC5C,iBACI,eACA,oBAAoB,eACpB,oBAAoB,sBACpB,cACA,oBAAoB,SACxB;EACA;CACJ;CAEA,IAAI,CAAC,2BAA2B,QAAQ,oBAAoB,GACxD;CAGJ,oBACI,eACA,oBAAoB,eACpB,oBAAoB,sBACpB,cACA,oBAAoB,SACxB;AACJ;AAEA,SAAS,2BACL,SACoB;CACpB,OAAO,iBAEJ,OAAO,GAAG,CAAC,GAAG,UAA+C;EAC5D,MAAM,sBAAsB,0BAA0B,GAAG,OAAO;EAEhE,EAAE,IAAI,UAAU,oBAAoB,aAAa;EACjD,MAAM,KAAK;EACX,uBAAuB,GAAG,SAAS,mBAAmB;CAC1D,CAAC;AACL"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { StringifiedArgument } from "./console_text.js";
|
|
2
|
+
import { LogEntry } from "./logger_factory.js";
|
|
3
|
+
/** A log entry with its arguments already turned into text. */
|
|
4
|
+
type LogFileEntry = Readonly<Omit<LogEntry, "args"> & {
|
|
5
|
+
args: readonly StringifiedArgument[];
|
|
6
|
+
}>;
|
|
7
|
+
type LogFileWriter = (filePath: string, entry: LogFileEntry) => void;
|
|
8
|
+
export type { LogFileEntry, LogFileWriter };
|
|
9
|
+
//# sourceMappingURL=log_file.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"log_file.d.ts","names":[],"sources":["../src/log_file.ts"],"mappings":";;;KAcK,eAAe,SAChB,KAAK;EACD,eAAe;;KAIlB,iBAAiB,kBAAkB,OAAO"}
|
package/dist/log_file.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { buildLogMessage, formatOpenTelemetryContextLabel } from "./logger_factory.js";
|
|
2
|
+
import { escapeFileCharacters } from "./serialize_value.js";
|
|
3
|
+
// src/log_file.ts
|
|
4
|
+
const LINE_BREAK = "\n";
|
|
5
|
+
const ARGUMENT_SEPARATOR = " ";
|
|
6
|
+
const STACK_CONTINUATION_PREFIX = " ";
|
|
7
|
+
const EMPTY_LENGTH = 0;
|
|
8
|
+
function formatFileArgument(argument) {
|
|
9
|
+
if (argument.kind === "object" && "jsonValue" in argument) return escapeFileCharacters(JSON.stringify(argument.jsonValue));
|
|
10
|
+
return escapeFileCharacters(argument.text);
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The file line is the console line without colors and with the ISO timestamp:
|
|
14
|
+
* the header, then every argument, separated by a space the way `console.log`
|
|
15
|
+
* separates them.
|
|
16
|
+
*
|
|
17
|
+
* @param {LogFileEntry} entry - The log call.
|
|
18
|
+
* @returns {string} One log file line, without the trailing line break.
|
|
19
|
+
*/
|
|
20
|
+
function buildFileLine(entry) {
|
|
21
|
+
return [escapeFileCharacters(buildLogMessage(new Date(entry.epochMilliseconds).toISOString(), `[${entry.level}]`, entry.loggerName, formatOpenTelemetryContextLabel(entry.openTelemetryContext), entry.message)), ...entry.args.map(formatFileArgument)].join(ARGUMENT_SEPARATOR);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* A stack trace is several lines. Every one of them starts with a tab in the
|
|
25
|
+
* file, while every log entry starts with a timestamp, so a reader can tell the
|
|
26
|
+
* continuation lines of an entry from the next entry.
|
|
27
|
+
*
|
|
28
|
+
* @param {string} stackTrace - The plain stack trace.
|
|
29
|
+
* @returns {string} The stack trace, each line tab-prefixed and escaped.
|
|
30
|
+
*/
|
|
31
|
+
function formatFileStackTrace(stackTrace) {
|
|
32
|
+
return stackTrace.split(LINE_BREAK).map((line) => {
|
|
33
|
+
return `${STACK_CONTINUATION_PREFIX}${escapeFileCharacters(line)}`;
|
|
34
|
+
}).join(LINE_BREAK);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The log file writer for runtimes that can append to a file. Only those import
|
|
38
|
+
* this module, so the `web` entry never bundles it.
|
|
39
|
+
*
|
|
40
|
+
* @param {(filePath: string, content: string) => void} appendTextFileSync -
|
|
41
|
+
* Appends text to the file, creating it when it is missing.
|
|
42
|
+
* @returns {LogFileWriter} Writes one entry, then its stack trace, if any.
|
|
43
|
+
*/
|
|
44
|
+
function createLogFileWriter(appendTextFileSync) {
|
|
45
|
+
return (filePath, entry) => {
|
|
46
|
+
appendTextFileSync(filePath, `${buildFileLine(entry)}${LINE_BREAK}`);
|
|
47
|
+
if (entry.stackTrace.length > EMPTY_LENGTH) appendTextFileSync(filePath, `${formatFileStackTrace(entry.stackTrace)}${LINE_BREAK}`);
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
export { createLogFileWriter };
|
|
51
|
+
|
|
52
|
+
//# sourceMappingURL=log_file.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"log_file.js","names":[],"sources":["../src/log_file.ts"],"sourcesContent":["import type { StringifiedArgument } from \"./console_text\";\nimport {\n buildLogMessage,\n formatOpenTelemetryContextLabel,\n} from \"./logger_factory\";\nimport type { LogEntry } from \"./logger_factory\";\nimport { escapeFileCharacters } from \"./serialize_value\";\n\nconst LINE_BREAK = \"\\n\";\nconst ARGUMENT_SEPARATOR = \" \";\nconst STACK_CONTINUATION_PREFIX = \"\\t\";\nconst EMPTY_LENGTH = 0;\n\n/** A log entry with its arguments already turned into text. */\ntype LogFileEntry = Readonly<\n Omit<LogEntry, \"args\"> & {\n args: readonly StringifiedArgument[];\n }\n>;\n\ntype LogFileWriter = (filePath: string, entry: LogFileEntry) => void;\n\nfunction formatFileArgument(argument: StringifiedArgument): string {\n // Objects use their compact, single-line JSON. JSON already escaped the\n // control characters below U+0020; the rest (DEL, C1, U+2028, bidi\n // controls) is escaped here, and an escape inside a JSON string is still\n // valid JSON.\n if (argument.kind === \"object\" && \"jsonValue\" in argument) {\n return escapeFileCharacters(JSON.stringify(argument.jsonValue));\n }\n\n return escapeFileCharacters(argument.text);\n}\n\n/**\n * The file line is the console line without colors and with the ISO timestamp:\n * the header, then every argument, separated by a space the way `console.log`\n * separates them.\n *\n * @param {LogFileEntry} entry - The log call.\n * @returns {string} One log file line, without the trailing line break.\n */\nfunction buildFileLine(entry: LogFileEntry): string {\n const header = escapeFileCharacters(\n buildLogMessage(\n new Date(entry.epochMilliseconds).toISOString(),\n `[${entry.level}]`,\n entry.loggerName,\n formatOpenTelemetryContextLabel(entry.openTelemetryContext),\n entry.message,\n ),\n );\n\n return [header, ...entry.args.map(formatFileArgument)].join(\n ARGUMENT_SEPARATOR,\n );\n}\n\n/**\n * A stack trace is several lines. Every one of them starts with a tab in the\n * file, while every log entry starts with a timestamp, so a reader can tell the\n * continuation lines of an entry from the next entry.\n *\n * @param {string} stackTrace - The plain stack trace.\n * @returns {string} The stack trace, each line tab-prefixed and escaped.\n */\nfunction formatFileStackTrace(stackTrace: string): string {\n return stackTrace\n .split(LINE_BREAK)\n .map((line) => {\n return `${STACK_CONTINUATION_PREFIX}${escapeFileCharacters(line)}`;\n })\n .join(LINE_BREAK);\n}\n\n/**\n * The log file writer for runtimes that can append to a file. Only those import\n * this module, so the `web` entry never bundles it.\n *\n * @param {(filePath: string, content: string) => void} appendTextFileSync -\n * Appends text to the file, creating it when it is missing.\n * @returns {LogFileWriter} Writes one entry, then its stack trace, if any.\n */\nfunction createLogFileWriter(\n appendTextFileSync: (filePath: string, content: string) => void,\n): LogFileWriter {\n return (filePath, entry) => {\n appendTextFileSync(filePath, `${buildFileLine(entry)}${LINE_BREAK}`);\n\n if (entry.stackTrace.length > EMPTY_LENGTH) {\n appendTextFileSync(\n filePath,\n `${formatFileStackTrace(entry.stackTrace)}${LINE_BREAK}`,\n );\n }\n };\n}\n\nexport { createLogFileWriter };\nexport type { LogFileEntry, LogFileWriter };\n"],"mappings":";;;AAQA,MAAM,aAAa;AACnB,MAAM,qBAAqB;AAC3B,MAAM,4BAA4B;AAClC,MAAM,eAAe;AAWrB,SAAS,mBAAmB,UAAuC;CAK/D,IAAI,SAAS,SAAS,YAAY,eAAe,UAC7C,OAAO,qBAAqB,KAAK,UAAU,SAAS,SAAS,CAAC;CAGlE,OAAO,qBAAqB,SAAS,IAAI;AAC7C;;;;;;;;;AAUA,SAAS,cAAc,OAA6B;CAWhD,OAAO,CAVQ,qBACX,gBACI,IAAI,KAAK,MAAM,iBAAiB,CAAC,CAAC,YAAY,GAC9C,IAAI,MAAM,MAAM,IAChB,MAAM,YACN,gCAAgC,MAAM,oBAAoB,GAC1D,MAAM,OACV,CAGS,GAAG,GAAG,MAAM,KAAK,IAAI,kBAAkB,CAAC,CAAC,CAAC,KACnD,kBACJ;AACJ;;;;;;;;;AAUA,SAAS,qBAAqB,YAA4B;CACtD,OAAO,WACF,MAAM,UAAU,CAAC,CACjB,KAAK,SAAS;EACX,OAAO,GAAG,4BAA4B,qBAAqB,IAAI;CACnE,CAAC,CAAC,CACD,KAAK,UAAU;AACxB;;;;;;;;;AAUA,SAAS,oBACL,oBACa;CACb,QAAQ,UAAU,UAAU;EACxB,mBAAmB,UAAU,GAAG,cAAc,KAAK,IAAI,YAAY;EAEnE,IAAI,MAAM,WAAW,SAAS,cAC1B,mBACI,UACA,GAAG,qBAAqB,MAAM,UAAU,IAAI,YAChD;CAER;AACJ"}
|
package/dist/logger.d.ts
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
import { LogLevel, LoggerBase, LoggerOptions, LoggerParent } from "./logger_factory.js";
|
|
2
|
-
//#region src/logger.d.ts
|
|
3
2
|
declare class Logger extends LoggerBase {
|
|
4
3
|
constructor(name: string, parent?: LoggerParent, options?: LoggerOptions);
|
|
5
4
|
}
|
|
6
|
-
//#endregion
|
|
7
5
|
export { type LogLevel, Logger, type LoggerOptions };
|
|
8
6
|
//# sourceMappingURL=logger.d.ts.map
|
package/dist/logger.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logger.d.ts","names":[],"sources":["../src/logger.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"logger.d.ts","names":[],"sources":["../src/logger.ts"],"mappings":";cAIM,eAAe;EACjB,YACI,cACA,SAAS,cACT,UAAS"}
|
package/dist/logger.js
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import { LoggerBase } from "./logger_factory.js";
|
|
2
2
|
import { nodeRuntime } from "./node_runtime.js";
|
|
3
|
-
|
|
3
|
+
// src/logger.ts
|
|
4
4
|
var Logger = class Logger extends LoggerBase {
|
|
5
5
|
constructor(name, parent, options = {}) {
|
|
6
6
|
super(Logger, nodeRuntime, name, parent, options);
|
|
7
7
|
}
|
|
8
8
|
};
|
|
9
|
-
//#endregion
|
|
10
9
|
export { Logger };
|
|
11
10
|
|
|
12
11
|
//# sourceMappingURL=logger.js.map
|
package/dist/logger.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logger.js","names":[],"sources":["../src/logger.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"logger.js","names":[],"sources":["../src/logger.ts"],"sourcesContent":["import { LoggerBase } from \"./logger_factory\";\nimport type { LoggerOptions, LoggerParent, LogLevel } from \"./logger_factory\";\nimport { nodeRuntime } from \"./node_runtime\";\n\nclass Logger extends LoggerBase {\n constructor(\n name: string,\n parent?: LoggerParent,\n options: LoggerOptions = {},\n ) {\n super(Logger, nodeRuntime, name, parent, options);\n }\n}\n\nexport { Logger };\n\nexport type { LoggerOptions, LogLevel };\n"],"mappings":";;;AAIA,IAAM,SAAN,MAAM,eAAe,WAAW;CAC5B,YACI,MACA,QACA,UAAyB,CAAC,GAC5B;EACE,MAAM,QAAQ,aAAa,MAAM,QAAQ,OAAO;CACpD;AACJ"}
|