@logtape/adaptor-log4js 2.0.0-dev.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/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright 2024–2025 Hong Minhee
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,201 @@
1
+ <!-- deno-fmt-ignore-file -->
2
+
3
+ @logtape/adaptor-log4js
4
+ =======================
5
+
6
+ [![JSR][JSR badge]][JSR]
7
+ [![npm][npm badge]][npm]
8
+
9
+ *@logtape/adaptor-log4js* is a [LogTape] adapter that forwards log records to
10
+ [log4js] loggers, enabling seamless integration between LogTape-enabled
11
+ libraries and applications using log4js for logging infrastructure.
12
+
13
+ [JSR badge]: https://jsr.io/badges/@logtape/adaptor-log4js
14
+ [JSR]: https://jsr.io/@logtape/adaptor-log4js
15
+ [npm badge]: https://img.shields.io/npm/v/@logtape/adaptor-log4js?logo=npm
16
+ [npm]: https://www.npmjs.com/package/@logtape/adaptor-log4js
17
+ [LogTape]: https://logtape.org/
18
+ [log4js]: https://log4js-node.github.io/log4js-node/
19
+
20
+
21
+ Installation
22
+ ------------
23
+
24
+ ~~~~ sh
25
+ deno add jsr:@logtape/adaptor-log4js # for Deno
26
+ npm add @logtape/adaptor-log4js # for npm
27
+ pnpm add @logtape/adaptor-log4js # for pnpm
28
+ yarn add @logtape/adaptor-log4js # for Yarn
29
+ bun add @logtape/adaptor-log4js # for Bun
30
+ ~~~~
31
+
32
+
33
+ Usage
34
+ -----
35
+
36
+ ### Quick setup
37
+
38
+ The simplest way to integrate LogTape with log4js is using the auto-installer:
39
+
40
+ ~~~~ typescript
41
+ import log4js from "log4js";
42
+
43
+ // Configure log4js first
44
+ log4js.configure({
45
+ appenders: { out: { type: "stdout" } },
46
+ categories: { default: { appenders: ["out"], level: "info" } }
47
+ });
48
+
49
+ // Simply import to automatically set up the adapter
50
+ import "@logtape/adaptor-log4js/install";
51
+
52
+ // Now all LogTape logs will be routed to log4js
53
+ import { getLogger } from "@logtape/logtape";
54
+ const logger = getLogger("my-app");
55
+ logger.info("This will be logged through log4js");
56
+ ~~~~
57
+
58
+ ### Using the `install()` function
59
+
60
+ For more control, use the `install()` function:
61
+
62
+ ~~~~ typescript
63
+ import log4js from "log4js";
64
+ import { install } from "@logtape/adaptor-log4js";
65
+
66
+ log4js.configure({
67
+ appenders: { out: { type: "stdout" } },
68
+ categories: { default: { appenders: ["out"], level: "info" } }
69
+ });
70
+
71
+ // With default options (category-based loggers)
72
+ install(log4js);
73
+
74
+ // Or with a custom logger
75
+ const customLogger = log4js.getLogger("myapp");
76
+ install(log4js, customLogger);
77
+
78
+ // Or with custom options
79
+ install(log4js, undefined, {
80
+ categoryMapper: (cat) => cat.join("::"),
81
+ contextStrategy: "args"
82
+ });
83
+ ~~~~
84
+
85
+ ### Manual configuration
86
+
87
+ For full control over the log4js integration, configure LogTape manually:
88
+
89
+ ~~~~ typescript
90
+ import { configure } from "@logtape/logtape";
91
+ import { getLog4jsSink } from "@logtape/adaptor-log4js";
92
+ import log4js from "log4js";
93
+
94
+ log4js.configure({
95
+ appenders: { out: { type: "stdout" } },
96
+ categories: { default: { appenders: ["out"], level: "info" } }
97
+ });
98
+
99
+ await configure({
100
+ sinks: {
101
+ log4js: getLog4jsSink(log4js, undefined, {
102
+ categoryMapper: (cat) => cat.join("."),
103
+ contextStrategy: "mdc",
104
+ contextPreservation: "preserve"
105
+ })
106
+ },
107
+ loggers: [
108
+ { category: "my-library", sinks: ["log4js"] }
109
+ ]
110
+ });
111
+ ~~~~
112
+
113
+
114
+ Category mapping
115
+ ----------------
116
+
117
+ By default, LogTape categories are mapped to log4js categories using dot
118
+ notation. For example, LogTape category `["app", "database", "query"]` becomes
119
+ log4js category `"app.database.query"`.
120
+
121
+ You can customize this behavior using the `categoryMapper` option:
122
+
123
+ ~~~~ typescript
124
+ import { getLog4jsSink } from "@logtape/adaptor-log4js";
125
+
126
+ // Use :: as separator
127
+ const sink = getLog4jsSink(log4js, undefined, {
128
+ categoryMapper: (cat) => cat.join("::")
129
+ });
130
+
131
+ // Custom logic
132
+ const sink2 = getLog4jsSink(log4js, undefined, {
133
+ categoryMapper: (cat) => {
134
+ if (cat.length === 0) return "default";
135
+ return cat.slice(0, 2).join("."); // Only use first two parts
136
+ }
137
+ });
138
+ ~~~~
139
+
140
+
141
+ Context handling
142
+ ----------------
143
+
144
+ The adapter supports two strategies for handling LogTape properties.
145
+ The type system ensures that `contextPreservation` can only be used with
146
+ the MDC strategy:
147
+
148
+ ### MDC (Mapped Diagnostic Context) strategy (default)
149
+
150
+ Uses log4js's built-in context feature to add LogTape properties:
151
+
152
+ ~~~~ typescript
153
+ const sink = getLog4jsSink(log4js, undefined, {
154
+ contextStrategy: "mdc"
155
+ });
156
+ ~~~~
157
+
158
+ When using MDC strategy, you can control how existing context is handled:
159
+
160
+ ~~~~ typescript
161
+ // Preserve existing context (default)
162
+ // LogTape properties are added during logging, then removed
163
+ const sink1 = getLog4jsSink(log4js, undefined, {
164
+ contextStrategy: "mdc",
165
+ contextPreservation: "preserve"
166
+ });
167
+
168
+ // Merge with existing context
169
+ // LogTape properties are added and left in context
170
+ const sink2 = getLog4jsSink(log4js, undefined, {
171
+ contextStrategy: "mdc",
172
+ contextPreservation: "merge"
173
+ });
174
+
175
+ // Replace existing context
176
+ // Existing context is cleared before adding LogTape properties
177
+ const sink3 = getLog4jsSink(log4js, undefined, {
178
+ contextStrategy: "mdc",
179
+ contextPreservation: "replace"
180
+ });
181
+ ~~~~
182
+
183
+ ### Args strategy
184
+
185
+ Passes LogTape properties as additional arguments to log methods.
186
+ Note that `contextPreservation` is not available with this strategy:
187
+
188
+ ~~~~ typescript
189
+ const sink = getLog4jsSink(log4js, undefined, {
190
+ contextStrategy: "args"
191
+ // contextPreservation is not allowed here - TypeScript will error
192
+ });
193
+ ~~~~
194
+
195
+
196
+ Docs
197
+ ----
198
+
199
+ See the [API reference] on JSR for further details.
200
+
201
+ [API reference]: https://jsr.io/@logtape/adaptor-log4js/doc
@@ -0,0 +1,7 @@
1
+ const require_src = require('./src-tAG616xa.cjs');
2
+ const log4js = require_src.__toESM(require("log4js"));
3
+
4
+ //#region src/install.ts
5
+ require_src.install(log4js.default);
6
+
7
+ //#endregion
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,7 @@
1
+ import { install } from "./src-Cb2nEPMQ.js";
2
+ import log4js from "log4js";
3
+
4
+ //#region src/install.ts
5
+ install(log4js);
6
+
7
+ //#endregion
package/dist/mod.cjs ADDED
@@ -0,0 +1,4 @@
1
+ const require_src = require('./src-tAG616xa.cjs');
2
+
3
+ exports.getLog4jsSink = require_src.getLog4jsSink;
4
+ exports.install = require_src.install;
package/dist/mod.d.cts ADDED
@@ -0,0 +1,325 @@
1
+ import { LogLevel, Sink } from "@logtape/logtape";
2
+ import log4js from "log4js";
3
+
4
+ //#region src/mod.d.ts
5
+
6
+ /**
7
+ * Logger interface for log4js-compatible loggers.
8
+ * @since 2.0.0
9
+ */
10
+ interface Logger {
11
+ trace: LogMethod;
12
+ debug: LogMethod;
13
+ info: LogMethod;
14
+ warn: LogMethod;
15
+ error: LogMethod;
16
+ fatal: LogMethod;
17
+ addContext: (key: string, value: unknown) => void;
18
+ removeContext: (key: string) => void;
19
+ clearContext: () => void;
20
+ }
21
+ /**
22
+ * Log method signature for log4js.
23
+ * @since 2.0.0
24
+ */
25
+ interface LogMethod {
26
+ (message: string, ...args: unknown[]): void;
27
+ }
28
+ /**
29
+ * log4js log level type.
30
+ * @since 2.0.0
31
+ */
32
+ type Log4jsLevel = "trace" | "debug" | "info" | "warn" | "error" | "fatal";
33
+ /**
34
+ * Strategy for handling LogTape properties in log4js.
35
+ * @since 2.0.0
36
+ */
37
+ type ContextStrategy = "mdc" | "args";
38
+ /**
39
+ * Strategy for handling existing log4js context.
40
+ * @since 2.0.0
41
+ */
42
+ type ContextPreservation = "preserve" | "merge" | "replace";
43
+ /**
44
+ * Base configuration options shared by all context strategies.
45
+ * @since 2.0.0
46
+ */
47
+ interface Log4jsSinkOptionsBase {
48
+ /**
49
+ * Mapping between LogTape log levels and log4js log levels.
50
+ *
51
+ * By default, LogTape levels are mapped as follows:
52
+ *
53
+ * - `trace` → `trace`
54
+ * - `debug` → `debug`
55
+ * - `info` → `info`
56
+ * - `warning` → `warn`
57
+ * - `error` → `error`
58
+ * - `fatal` → `fatal`
59
+ */
60
+ readonly levelsMap?: Readonly<Record<LogLevel, Log4jsLevel>>;
61
+ /**
62
+ * Custom mapper function to convert LogTape categories to log4js category strings.
63
+ *
64
+ * By default, LogTape categories are joined with dots (e.g., `["app", "db"]` becomes `"app.db"`).
65
+ *
66
+ * @param category The LogTape category array
67
+ * @returns The log4js category string
68
+ * @default (category) => category.join(".")
69
+ *
70
+ * @example
71
+ * ```typescript
72
+ * // Use :: as separator
73
+ * categoryMapper: (cat) => cat.join("::")
74
+ * ```
75
+ *
76
+ * @example
77
+ * ```typescript
78
+ * // Custom logic for category mapping
79
+ * categoryMapper: (cat) => {
80
+ * if (cat.length === 0) return "default";
81
+ * return cat.join(".");
82
+ * }
83
+ * ```
84
+ */
85
+ readonly categoryMapper?: (category: readonly string[]) => string;
86
+ /**
87
+ * Custom formatter for interpolated values in log messages.
88
+ *
89
+ * This function is used to convert values that are interpolated into
90
+ * log messages (e.g., the `name` in
91
+ * `logger.info("Hello, {name}!", { name: "world" })`).
92
+ *
93
+ * @param value The value to format
94
+ * @returns A string representation of the value
95
+ * @default `inspect` (from `node:util` module)
96
+ */
97
+ readonly valueFormatter?: (value: unknown) => string;
98
+ }
99
+ /**
100
+ * Configuration options for log4js sink with MDC (Mapped Diagnostic Context) strategy.
101
+ * @since 2.0.0
102
+ */
103
+ interface Log4jsSinkOptionsMdc extends Log4jsSinkOptionsBase {
104
+ /**
105
+ * Strategy for handling LogTape properties.
106
+ *
107
+ * Use `"mdc"` to leverage log4js's built-in MDC (Mapped Diagnostic Context) feature.
108
+ *
109
+ * @default "mdc"
110
+ */
111
+ readonly contextStrategy?: "mdc";
112
+ /**
113
+ * Strategy for handling existing log4js context when using MDC strategy.
114
+ *
115
+ * - `"preserve"` (default): Preserve existing context by saving and restoring it
116
+ * - `"merge"`: Merge LogTape properties with existing context (existing values take precedence)
117
+ * - `"replace"`: Replace existing context with LogTape properties
118
+ *
119
+ * @default "preserve"
120
+ *
121
+ * @example
122
+ * ```typescript
123
+ * // Preserve existing context (default)
124
+ * const sink = getLog4jsSink(undefined, undefined, {
125
+ * contextStrategy: "mdc",
126
+ * contextPreservation: "preserve"
127
+ * });
128
+ * ```
129
+ *
130
+ * @example
131
+ * ```typescript
132
+ * // Merge with existing context
133
+ * const sink = getLog4jsSink(undefined, undefined, {
134
+ * contextStrategy: "mdc",
135
+ * contextPreservation: "merge"
136
+ * });
137
+ * ```
138
+ */
139
+ readonly contextPreservation?: ContextPreservation;
140
+ }
141
+ /**
142
+ * Configuration options for log4js sink with args strategy.
143
+ * @since 2.0.0
144
+ */
145
+ interface Log4jsSinkOptionsArgs extends Log4jsSinkOptionsBase {
146
+ /**
147
+ * Strategy for handling LogTape properties.
148
+ *
149
+ * Use `"args"` to pass properties as additional arguments to log methods.
150
+ */
151
+ readonly contextStrategy: "args";
152
+ }
153
+ /**
154
+ * Configuration options for the log4js sink.
155
+ *
156
+ * This is a discriminated union type based on the `contextStrategy` option.
157
+ * When `contextStrategy` is `"mdc"` (or omitted), the `contextPreservation` option
158
+ * is available. When `contextStrategy` is `"args"`, the `contextPreservation` option
159
+ * is not allowed.
160
+ *
161
+ * @example Basic usage with default options (MDC strategy)
162
+ * ```typescript
163
+ * const sink = getLog4jsSink();
164
+ * ```
165
+ *
166
+ * @example Custom level mapping
167
+ * ```typescript
168
+ * const sink = getLog4jsSink(undefined, undefined, {
169
+ * levelsMap: {
170
+ * "trace": "debug",
171
+ * "debug": "debug",
172
+ * "info": "info",
173
+ * "warning": "warn",
174
+ * "error": "error",
175
+ * "fatal": "fatal"
176
+ * }
177
+ * });
178
+ * ```
179
+ *
180
+ * @example Custom category mapping
181
+ * ```typescript
182
+ * const sink = getLog4jsSink(undefined, undefined, {
183
+ * categoryMapper: (category) => category.join("::")
184
+ * });
185
+ * ```
186
+ *
187
+ * @example Using MDC strategy with preserve (default)
188
+ * ```typescript
189
+ * const sink = getLog4jsSink(undefined, undefined, {
190
+ * contextStrategy: "mdc",
191
+ * contextPreservation: "preserve"
192
+ * });
193
+ * ```
194
+ *
195
+ * @example Using args strategy
196
+ * ```typescript
197
+ * const sink = getLog4jsSink(undefined, undefined, {
198
+ * contextStrategy: "args"
199
+ * // contextPreservation is not allowed here
200
+ * });
201
+ * ```
202
+ *
203
+ * @since 2.0.0
204
+ */
205
+ type Log4jsSinkOptions = Log4jsSinkOptionsMdc | Log4jsSinkOptionsArgs;
206
+ /**
207
+ * Creates a LogTape sink that forwards log records to a log4js logger.
208
+ *
209
+ * This function creates a sink function that can be used with LogTape's
210
+ * configuration system. The sink will format LogTape log records and
211
+ * forward them to the provided log4js logger instance or create one
212
+ * based on the LogTape category.
213
+ *
214
+ * @example Basic usage with default log4js logger
215
+ * ```typescript
216
+ * import log4js from "log4js";
217
+ * import { configure } from "@logtape/logtape";
218
+ * import { getLog4jsSink } from "@logtape/adaptor-log4js";
219
+ *
220
+ * log4js.configure({
221
+ * appenders: { out: { type: "stdout" } },
222
+ * categories: { default: { appenders: ["out"], level: "info" } }
223
+ * });
224
+ *
225
+ * await configure({
226
+ * sinks: {
227
+ * log4js: getLog4jsSink()
228
+ * },
229
+ * loggers: [
230
+ * { category: ["myapp"], sinks: ["log4js"] }
231
+ * ]
232
+ * });
233
+ * ```
234
+ *
235
+ * @example With custom log4js logger
236
+ * ```typescript
237
+ * import log4js from "log4js";
238
+ * import { getLog4jsSink } from "@logtape/adaptor-log4js";
239
+ *
240
+ * const logger = log4js.getLogger("custom");
241
+ * const sink = getLog4jsSink(logger);
242
+ * ```
243
+ *
244
+ * @example With custom options
245
+ * ```typescript
246
+ * const sink = getLog4jsSink(undefined, {
247
+ * categoryMapper: (cat) => cat.join("::"),
248
+ * contextStrategy: "args",
249
+ * levelsMap: {
250
+ * "trace": "debug",
251
+ * "debug": "debug",
252
+ * "info": "info",
253
+ * "warning": "warn",
254
+ * "error": "error",
255
+ * "fatal": "fatal"
256
+ * }
257
+ * });
258
+ * ```
259
+ *
260
+ * @param log4jsModule The log4js module instance. If not provided, log4js will be imported dynamically.
261
+ * @param logger The log4js logger instance to forward logs to. If not provided,
262
+ * a logger will be created for each LogTape category using log4js.getLogger().
263
+ * @param options Configuration options for the sink behavior.
264
+ * @returns A sink function that can be used with LogTape's configure() function.
265
+ * @since 2.0.0
266
+ */
267
+ declare function getLog4jsSink(log4jsModule?: typeof log4js, logger?: Logger, options?: Log4jsSinkOptions): Sink;
268
+ /**
269
+ * Automatically configures LogTape to route all logs to log4js.
270
+ *
271
+ * This is a convenience function that automatically sets up LogTape to forward
272
+ * all log records to log4js. By default, it creates loggers based on LogTape
273
+ * categories using log4js.getLogger(), but you can provide a custom logger
274
+ * as the second parameter.
275
+ *
276
+ * @param log4jsModule The log4js module instance. If not provided, log4js will be imported dynamically.
277
+ * @param logger Optional log4js logger instance to use for all logs.
278
+ * @param options Configuration options for the log4js sink behavior.
279
+ *
280
+ * @example Basic auto-configuration
281
+ * ```typescript
282
+ * import log4js from "log4js";
283
+ * import { install } from "@logtape/adaptor-log4js";
284
+ *
285
+ * log4js.configure({
286
+ * appenders: { out: { type: "stdout" } },
287
+ * categories: { default: { appenders: ["out"], level: "info" } }
288
+ * });
289
+ *
290
+ * // Automatically route all LogTape logs to log4js
291
+ * install(log4js);
292
+ *
293
+ * // Now any LogTape-enabled library will log through log4js
294
+ * import { getLogger } from "@logtape/logtape";
295
+ * const logger = getLogger("my-app");
296
+ * logger.info("This will be logged through log4js");
297
+ * ```
298
+ *
299
+ * @example Auto-configuration with custom logger
300
+ * ```typescript
301
+ * import log4js from "log4js";
302
+ * import { install } from "@logtape/adaptor-log4js";
303
+ *
304
+ * const customLogger = log4js.getLogger("myapp");
305
+ *
306
+ * // Install with custom logger
307
+ * install(log4js, customLogger);
308
+ * ```
309
+ *
310
+ * @example Auto-configuration with custom options
311
+ * ```typescript
312
+ * import log4js from "log4js";
313
+ * import { install } from "@logtape/adaptor-log4js";
314
+ *
315
+ * install(log4js, undefined, {
316
+ * categoryMapper: (cat) => cat.join("::"),
317
+ * contextStrategy: "args"
318
+ * });
319
+ * ```
320
+ *
321
+ * @since 2.0.0
322
+ */
323
+ declare function install(log4jsModule: typeof log4js, logger?: Logger, options?: Log4jsSinkOptions): void;
324
+ //#endregion
325
+ export { ContextPreservation, ContextStrategy, Log4jsLevel, Log4jsSinkOptions, Log4jsSinkOptionsArgs, Log4jsSinkOptionsBase, Log4jsSinkOptionsMdc, LogMethod, Logger, getLog4jsSink, install };