@jmlq/logger 0.1.0-alpha.7 → 0.1.0-alpha.9

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.
Files changed (147) hide show
  1. package/README.md +225 -733
  2. package/architecture.md +171 -0
  3. package/dist/examples/data-source-service.example.d.ts +3 -0
  4. package/dist/examples/data-source-service.example.js +174 -0
  5. package/dist/examples/flush-buffers-use-case.example.d.ts +3 -0
  6. package/dist/examples/flush-buffers-use-case.example.js +60 -0
  7. package/dist/examples/get-logs-use-case.example.d.ts +3 -0
  8. package/dist/examples/get-logs-use-case.example.js +110 -0
  9. package/dist/examples/index.example.d.ts +8 -0
  10. package/dist/examples/index.example.js +116 -0
  11. package/dist/examples/logger-factory.example.d.ts +39 -0
  12. package/dist/examples/logger-factory.example.js +158 -0
  13. package/dist/examples/normalize-message.example.d.ts +3 -0
  14. package/dist/examples/normalize-message.example.js +80 -0
  15. package/dist/examples/pii-redactor.example.d.ts +3 -0
  16. package/dist/examples/pii-redactor.example.js +129 -0
  17. package/dist/examples/save-log-use-case.example.d.ts +3 -0
  18. package/dist/examples/save-log-use-case.example.js +150 -0
  19. package/dist/examples/to-log-level.example.d.ts +3 -0
  20. package/dist/examples/to-log-level.example.js +49 -0
  21. package/dist/examples/to-pii-regex.example.d.ts +3 -0
  22. package/dist/examples/to-pii-regex.example.js +75 -0
  23. package/dist/{presentation → src/application}/factory/create-logger.d.ts +1 -1
  24. package/dist/{presentation → src/application}/factory/create-logger.js +3 -3
  25. package/dist/src/application/factory/index.d.ts +1 -0
  26. package/dist/{presentation → src/application}/factory/index.js +1 -1
  27. package/dist/src/application/factory/logger.factory.d.ts +12 -0
  28. package/dist/src/application/factory/logger.factory.js +74 -0
  29. package/dist/src/application/index.d.ts +2 -0
  30. package/dist/src/application/index.js +18 -0
  31. package/dist/src/application/use-cases/flush-buffers.use-case.d.ts +6 -0
  32. package/dist/{application/use-cases/flush-buffers.js → src/application/use-cases/flush-buffers.use-case.js} +3 -3
  33. package/dist/src/application/use-cases/get-logs.use-case.d.ts +8 -0
  34. package/dist/{application/use-cases/get-logs.js → src/application/use-cases/get-logs.use-case.js} +3 -3
  35. package/dist/src/application/use-cases/index.d.ts +3 -0
  36. package/dist/{application → src/application}/use-cases/index.js +3 -3
  37. package/dist/src/application/use-cases/save-log.use-case.d.ts +8 -0
  38. package/dist/src/application/use-cases/save-log.use-case.js +26 -0
  39. package/dist/src/domain/index.d.ts +6 -0
  40. package/dist/src/domain/index.js +22 -0
  41. package/dist/src/domain/ports/create-logger-options.port.d.ts +7 -0
  42. package/dist/src/domain/ports/index.d.ts +6 -0
  43. package/dist/src/domain/ports/index.js +22 -0
  44. package/dist/src/domain/ports/log-datasource.port.d.ts +9 -0
  45. package/dist/src/domain/ports/logger-factory-config.port.d.ts +28 -0
  46. package/dist/src/domain/ports/logger-service.port.d.ts +19 -0
  47. package/dist/{domain/contracts/logger.d.ts → src/domain/ports/logger.port.d.ts} +0 -9
  48. package/dist/src/domain/ports/logger.port.js +2 -0
  49. package/dist/src/domain/ports/pii-redactor.port.d.ts +5 -0
  50. package/dist/src/domain/ports/pii-redactor.port.js +2 -0
  51. package/dist/src/domain/request/get-logs-filter.props.d.ts +9 -0
  52. package/dist/src/domain/request/get-logs-filter.props.js +2 -0
  53. package/dist/src/domain/request/index.d.ts +5 -0
  54. package/dist/src/domain/request/index.js +21 -0
  55. package/dist/src/domain/request/log.props.d.ts +7 -0
  56. package/dist/src/domain/request/log.props.js +2 -0
  57. package/dist/src/domain/request/pii-options.props.d.ts +8 -0
  58. package/dist/src/domain/request/pii-options.props.js +2 -0
  59. package/dist/src/domain/request/pii-replacement.props.d.ts +5 -0
  60. package/dist/src/domain/request/pii-replacement.props.js +2 -0
  61. package/dist/src/domain/request/save-log.props.d.ts +7 -0
  62. package/dist/src/domain/request/save-log.props.js +2 -0
  63. package/dist/src/domain/response/index.d.ts +1 -0
  64. package/dist/{domain/value-objects → src/domain/response}/index.js +1 -1
  65. package/dist/src/domain/response/log.response.d.ts +7 -0
  66. package/dist/src/domain/response/log.response.js +2 -0
  67. package/dist/src/domain/services/index.d.ts +4 -0
  68. package/dist/{domain/contracts → src/domain/services}/index.js +4 -3
  69. package/dist/src/domain/services/log-level.service.d.ts +2 -0
  70. package/dist/src/domain/services/log-level.service.js +27 -0
  71. package/dist/src/domain/services/message-normalizer.service.d.ts +3 -0
  72. package/dist/src/domain/services/message-normalizer.service.js +8 -0
  73. package/dist/src/domain/services/pii-pattern.service.d.ts +2 -0
  74. package/dist/src/domain/services/pii-pattern.service.js +13 -0
  75. package/dist/src/domain/services/pii-redactor.d.ts +10 -0
  76. package/dist/{domain → src/domain}/services/pii-redactor.js +8 -17
  77. package/dist/src/domain/services/pii-redactor.service.d.ts +10 -0
  78. package/dist/src/domain/services/pii-redactor.service.js +68 -0
  79. package/dist/src/domain/types/index.d.ts +1 -0
  80. package/dist/src/domain/types/index.js +17 -0
  81. package/dist/src/domain/types/log-message.type.d.ts +1 -0
  82. package/dist/src/domain/types/log-message.type.js +2 -0
  83. package/dist/src/domain/value-objects/index.d.ts +1 -0
  84. package/dist/{domain/services → src/domain/value-objects}/index.js +1 -1
  85. package/dist/{domain/value-objects/log-level.d.ts → src/domain/value-objects/log-level.vo.d.ts} +0 -1
  86. package/dist/src/domain/value-objects/log-level.vo.js +13 -0
  87. package/dist/src/index.d.ts +6 -0
  88. package/dist/src/index.js +22 -0
  89. package/dist/src/infrastructure/datasources/in-memory-log.datasource.d.ts +1 -0
  90. package/dist/src/infrastructure/datasources/in-memory-log.datasource.js +2 -0
  91. package/dist/src/infrastructure/datasources/index.d.ts +1 -0
  92. package/dist/{infrastructure/adapters → src/infrastructure/datasources}/index.js +1 -1
  93. package/dist/src/infrastructure/index.d.ts +1 -0
  94. package/dist/{domain/types → src/infrastructure}/index.js +1 -1
  95. package/dist/src/infrastructure/services/data-source-error-handler.type.d.ts +5 -0
  96. package/dist/src/infrastructure/services/data-source-error-handler.type.js +2 -0
  97. package/dist/src/infrastructure/services/datasource.service.d.ts +15 -0
  98. package/dist/src/infrastructure/services/datasource.service.js +63 -0
  99. package/dist/src/infrastructure/services/index.d.ts +2 -0
  100. package/dist/src/infrastructure/services/index.js +18 -0
  101. package/dist/tests/application/factory/logger-factory.spec.d.ts +1 -0
  102. package/dist/tests/application/factory/logger-factory.spec.js +161 -0
  103. package/dist/tests/application/use-cases/flush-buffers.use-case.spec.d.ts +1 -0
  104. package/dist/tests/application/use-cases/flush-buffers.use-case.spec.js +38 -0
  105. package/dist/tests/application/use-cases/get-logs.use-case.spec.d.ts +1 -0
  106. package/dist/tests/application/use-cases/get-logs.use-case.spec.js +114 -0
  107. package/dist/tests/application/use-cases/save-log.use-case.spec.d.ts +1 -0
  108. package/dist/tests/application/use-cases/save-log.use-case.spec.js +138 -0
  109. package/dist/tests/domain/services/log-level.service.spec.d.ts +1 -0
  110. package/dist/tests/domain/services/log-level.service.spec.js +68 -0
  111. package/dist/tests/domain/services/normalize-message.spec.d.ts +1 -0
  112. package/dist/tests/domain/services/normalize-message.spec.js +83 -0
  113. package/dist/tests/domain/services/pii-redactor.spec.d.ts +1 -0
  114. package/dist/tests/domain/services/pii-redactor.spec.js +170 -0
  115. package/dist/tests/domain/services/to-pii-regex.spec.d.ts +1 -0
  116. package/dist/tests/domain/services/to-pii-regex.spec.js +82 -0
  117. package/dist/tests/infrastructure/services/datasource.service.spec.d.ts +1 -0
  118. package/dist/tests/infrastructure/services/datasource.service.spec.js +128 -0
  119. package/dist/tests/test-utils/create-pii-redactor-mock.d.ts +5 -0
  120. package/dist/tests/test-utils/create-pii-redactor-mock.js +10 -0
  121. package/install.md +367 -0
  122. package/package.json +29 -19
  123. package/LICENSE +0 -21
  124. package/dist/application/use-cases/flush-buffers.d.ts +0 -6
  125. package/dist/application/use-cases/get-logs.d.ts +0 -7
  126. package/dist/application/use-cases/index.d.ts +0 -3
  127. package/dist/application/use-cases/save-log.d.ts +0 -13
  128. package/dist/application/use-cases/save-log.js +0 -30
  129. package/dist/domain/contracts/index.d.ts +0 -3
  130. package/dist/domain/contracts/log.datasource.d.ts +0 -8
  131. package/dist/domain/contracts/pii.d.ts +0 -5
  132. package/dist/domain/services/index.d.ts +0 -1
  133. package/dist/domain/services/pii-redactor.d.ts +0 -10
  134. package/dist/domain/types/index.d.ts +0 -1
  135. package/dist/domain/types/log.types.d.ts +0 -28
  136. package/dist/domain/value-objects/index.d.ts +0 -1
  137. package/dist/domain/value-objects/log-level.js +0 -37
  138. package/dist/index.d.ts +0 -5
  139. package/dist/index.js +0 -10
  140. package/dist/infrastructure/adapters/composite.datasource.d.ts +0 -11
  141. package/dist/infrastructure/adapters/composite.datasource.js +0 -46
  142. package/dist/infrastructure/adapters/index.d.ts +0 -1
  143. package/dist/presentation/factory/index.d.ts +0 -1
  144. /package/dist/{domain/contracts/log.datasource.js → src/domain/ports/create-logger-options.port.js} +0 -0
  145. /package/dist/{domain/contracts/logger.js → src/domain/ports/log-datasource.port.js} +0 -0
  146. /package/dist/{domain/contracts/pii.js → src/domain/ports/logger-factory-config.port.js} +0 -0
  147. /package/dist/{domain/types/log.types.js → src/domain/ports/logger-service.port.js} +0 -0
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const services_1 = require("../../../src/domain/services");
4
+ describe("toPiiRegex()", () => {
5
+ // ---------------------------------------------------------------------------
6
+ // 1️⃣ Patrón válido con flags por defecto (g)
7
+ // ---------------------------------------------------------------------------
8
+ it("debe crear un RegExp válido con flags 'g' por defecto", () => {
9
+ const props = {
10
+ pattern: "\\d+",
11
+ replaceWith: "[NUM]",
12
+ };
13
+ const regex = (0, services_1.toPiiRegex)(props);
14
+ expect(regex).toBeInstanceOf(RegExp);
15
+ expect(regex.source).toBe("\\d+");
16
+ expect(regex.flags).toBe("g");
17
+ const result = "abc123def456".replace(regex, props.replaceWith);
18
+ expect(result).toBe("abc[NUM]def[NUM]");
19
+ });
20
+ // ---------------------------------------------------------------------------
21
+ // 2️⃣ Patrón válido con flags personalizados
22
+ // ---------------------------------------------------------------------------
23
+ it("debe respetar los flags personalizados si son válidos", () => {
24
+ const props = {
25
+ pattern: "test",
26
+ flags: "gi",
27
+ replaceWith: "X",
28
+ };
29
+ const regex = (0, services_1.toPiiRegex)(props);
30
+ expect(regex.source).toBe("test");
31
+ expect(regex.flags).toBe("gi");
32
+ expect("TeSt 1, test 2".replace(regex, props.replaceWith)).toBe("X 1, X 2");
33
+ });
34
+ // ---------------------------------------------------------------------------
35
+ // 3️⃣ Patrón inválido → debe retornar el RegExp fallback /$a/
36
+ // ---------------------------------------------------------------------------
37
+ it("debe retornar un RegExp imposible (/\\$a/) si el patrón es inválido", () => {
38
+ const props = {
39
+ pattern: "[unclosed",
40
+ flags: "g",
41
+ replaceWith: "X",
42
+ };
43
+ const regex = (0, services_1.toPiiRegex)(props);
44
+ // El fallback esperado es /$a/
45
+ expect(regex).toBeInstanceOf(RegExp);
46
+ expect(regex.source).toBe("$a");
47
+ expect(regex.test("cualquier texto")).toBe(false);
48
+ });
49
+ // ---------------------------------------------------------------------------
50
+ // 4️⃣ Flags inválidos → también debe usar el fallback
51
+ // ---------------------------------------------------------------------------
52
+ it("debe usar el fallback si los flags son inválidos", () => {
53
+ const props = {
54
+ pattern: "\\d+",
55
+ flags: "z", // flag inválido
56
+ replaceWith: "X",
57
+ };
58
+ const regex = (0, services_1.toPiiRegex)(props);
59
+ expect(regex.source).toBe("$a");
60
+ expect(regex.test("123")).toBe(false);
61
+ });
62
+ // ---------------------------------------------------------------------------
63
+ // 5️⃣ Asegura que el fallback nunca hace match con ejemplos comunes
64
+ // ---------------------------------------------------------------------------
65
+ it("el fallback nunca debe hacer match con strings comunes", () => {
66
+ const props = {
67
+ pattern: "\\", // clarísimamente inválido
68
+ replaceWith: "X",
69
+ };
70
+ const regex = (0, services_1.toPiiRegex)(props);
71
+ const samples = [
72
+ "",
73
+ "abc",
74
+ "123",
75
+ "user@test.com",
76
+ "tarjeta 4111-1111-1111-1111",
77
+ ];
78
+ for (const s of samples) {
79
+ expect(regex.test(s)).toBe(false);
80
+ }
81
+ });
82
+ });
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const infrastructure_1 = require("src/infrastructure");
4
+ const src_1 = require("../../../src");
5
+ describe("DataSourceService", () => {
6
+ const log = {
7
+ level: src_1.LogLevel.INFO,
8
+ message: "test log",
9
+ timestamp: Date.now(),
10
+ meta: {
11
+ userId: "12345",
12
+ },
13
+ };
14
+ const makeDsMock = () => ({
15
+ name: "mock",
16
+ save: jest.fn(),
17
+ find: jest.fn(),
18
+ flush: jest.fn(),
19
+ dispose: jest.fn(),
20
+ });
21
+ beforeEach(() => {
22
+ jest.clearAllMocks();
23
+ });
24
+ // -------------------------------------------------------------------------
25
+ // SAVE
26
+ // -------------------------------------------------------------------------
27
+ test("save() debe ejecutar save en todos los datasources", async () => {
28
+ const ds1 = makeDsMock();
29
+ const ds2 = makeDsMock();
30
+ const service = new infrastructure_1.DataSourceService([ds1, ds2]);
31
+ await service.save(log);
32
+ expect(ds1.save).toHaveBeenCalledWith(log);
33
+ expect(ds2.save).toHaveBeenCalledWith(log);
34
+ expect(ds1.save).toHaveBeenCalledTimes(1);
35
+ expect(ds2.save).toHaveBeenCalledTimes(1);
36
+ });
37
+ test("save() debe continuar incluso si uno de los datasources falla y llamar al error handler", async () => {
38
+ const ds1 = makeDsMock();
39
+ const ds2 = makeDsMock();
40
+ ds1.save.mockResolvedValue(undefined);
41
+ ds2.save.mockRejectedValue(new Error("failure"));
42
+ const onError = jest.fn();
43
+ const service = new infrastructure_1.DataSourceService([ds1, ds2], onError);
44
+ await service.save(log);
45
+ expect(ds1.save).toHaveBeenCalled();
46
+ expect(ds2.save).toHaveBeenCalled();
47
+ expect(onError).toHaveBeenCalledTimes(1);
48
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({
49
+ operation: "save",
50
+ datasourceName: "mock",
51
+ }));
52
+ // Opcional: validar que la razón sea el Error original
53
+ expect(onError.mock.calls[0][0].reason).toBeInstanceOf(Error);
54
+ expect(onError.mock.calls[0][0].reason.message).toBe("failure");
55
+ });
56
+ // -------------------------------------------------------------------------
57
+ // FIND
58
+ // -------------------------------------------------------------------------
59
+ test("find() debe concatenar resultados de varios datasources y ordenarlos desc por timestamp", async () => {
60
+ const ds1 = makeDsMock();
61
+ const ds2 = makeDsMock();
62
+ const logs1 = [
63
+ { level: src_1.LogLevel.INFO, message: "a", timestamp: 100 },
64
+ { level: src_1.LogLevel.WARN, message: "b", timestamp: 300 },
65
+ ];
66
+ const logs2 = [
67
+ { level: src_1.LogLevel.ERROR, message: "c", timestamp: 200 },
68
+ ];
69
+ ds1.find.mockResolvedValue(logs1);
70
+ ds2.find.mockResolvedValue(logs2);
71
+ const service = new infrastructure_1.DataSourceService([ds1, ds2]);
72
+ const result = await service.find();
73
+ expect(result).toHaveLength(3);
74
+ expect(result.map((l) => l.timestamp)).toEqual([300, 200, 100]);
75
+ });
76
+ test("find() ignora datasources que retornen error en find() y llama al error handler", async () => {
77
+ const ds1 = makeDsMock();
78
+ const ds2 = makeDsMock();
79
+ ds1.find.mockRejectedValue(new Error("ds1 fail"));
80
+ ds2.find.mockResolvedValue([
81
+ { id: "1", level: src_1.LogLevel.INFO, message: "ok", timestamp: 123 },
82
+ ]);
83
+ const onError = jest.fn();
84
+ const service = new infrastructure_1.DataSourceService([ds1, ds2], onError);
85
+ const result = await service.find();
86
+ // Sigue devolviendo solo los logs válidos
87
+ expect(result).toHaveLength(1);
88
+ expect(result[0].level).toBe(src_1.LogLevel.INFO);
89
+ // Y registra el error del datasource que falló
90
+ expect(onError).toHaveBeenCalledTimes(1);
91
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({
92
+ operation: "find",
93
+ datasourceName: "mock",
94
+ }));
95
+ expect(onError.mock.calls[0][0].reason).toBeInstanceOf(Error);
96
+ expect(onError.mock.calls[0][0].reason.message).toBe("ds1 fail");
97
+ });
98
+ // -------------------------------------------------------------------------
99
+ // FLUSH
100
+ // -------------------------------------------------------------------------
101
+ test("flush() debe llamar flush en todos los datasources que implementen flush()", async () => {
102
+ const ds1 = makeDsMock();
103
+ const ds2 = makeDsMock();
104
+ const service = new infrastructure_1.DataSourceService([ds1, ds2]);
105
+ await service.flush();
106
+ expect(ds1.flush).toHaveBeenCalledTimes(1);
107
+ expect(ds2.flush).toHaveBeenCalledTimes(1);
108
+ });
109
+ // -------------------------------------------------------------------------
110
+ // DISPOSE
111
+ // -------------------------------------------------------------------------
112
+ test("dispose() debe llamar dispose en todos los datasources", async () => {
113
+ const ds1 = makeDsMock();
114
+ const ds2 = makeDsMock();
115
+ const service = new infrastructure_1.DataSourceService([ds1, ds2]);
116
+ await service.dispose();
117
+ expect(ds1.dispose).toHaveBeenCalledTimes(1);
118
+ expect(ds2.dispose).toHaveBeenCalledTimes(1);
119
+ });
120
+ // -------------------------------------------------------------------------
121
+ // CONSTRUCTOR DEFENSIVO
122
+ // -------------------------------------------------------------------------
123
+ test("constructor debe filtrar targets inválidos (null/undefined)", async () => {
124
+ const ds1 = makeDsMock();
125
+ const service = new infrastructure_1.DataSourceService([ds1, null, undefined]);
126
+ expect(service.targets).toHaveLength(1);
127
+ });
128
+ });
@@ -0,0 +1,5 @@
1
+ import { IPiiRedactor } from "../../src/domain/ports";
2
+ export type PiiRedactorMock = IPiiRedactor & {
3
+ redact: jest.Mock;
4
+ };
5
+ export declare function createPiiRedactorMock(): PiiRedactorMock;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createPiiRedactorMock = createPiiRedactorMock;
4
+ function createPiiRedactorMock() {
5
+ const redact = jest.fn((value) => value);
6
+ return {
7
+ redact,
8
+ updateOptions: jest.fn(),
9
+ };
10
+ }
package/install.md ADDED
@@ -0,0 +1,367 @@
1
+ # Guía de Instalación y Configuración para @jmlq/logger
2
+
3
+ ## Instalación
4
+
5
+ ```bash
6
+ npm install @jmlq/logger
7
+ ```
8
+
9
+ ## Configuración Básica
10
+
11
+ ### NestJS
12
+
13
+ 1. Crear el módulo de Logger
14
+
15
+ ```typescript
16
+ // src/logger/logger.module.ts
17
+ import { Module, Global } from "@nestjs/common";
18
+ import { ConfigModule, ConfigService } from "@nestjs/config";
19
+ import { LoggerFactory } from "@jmlq/logger";
20
+
21
+ @Global()
22
+ @Module({
23
+ imports: [ConfigModule],
24
+ providers: [
25
+ {
26
+ provide: "LOGGER",
27
+ useFactory: async (configService: ConfigService) => {
28
+ // Configurar datasources según necesidades
29
+ const datasources = [];
30
+
31
+ // Ejemplo: Plugin de filesystem (requiere @jmlq/logger-plugin-fs)
32
+ if (configService.get("LOG_FS_ENABLED") === "true") {
33
+ const { FileSystemDatasource } = await import(
34
+ "@jmlq/logger-plugin-fs"
35
+ );
36
+ datasources.push(
37
+ new FileSystemDatasource({
38
+ basePath: configService.get("LOG_FS_PATH", "./logs"),
39
+ })
40
+ );
41
+ }
42
+
43
+ return LoggerFactory.create({
44
+ datasources,
45
+ minLevel: configService.get("LOG_LEVEL", "info"),
46
+ redactorOptions: {
47
+ enabled: true,
48
+ deep: true,
49
+ includeDefaults: true,
50
+ },
51
+ });
52
+ },
53
+ inject: [ConfigService],
54
+ },
55
+ ],
56
+ exports: ["LOGGER"],
57
+ })
58
+ export class LoggerModule {}
59
+ ```
60
+
61
+ 2. Usar en servicios
62
+
63
+ ```typescript
64
+ // src/users/users.service.ts
65
+ import { Injectable, Inject } from "@nestjs/common";
66
+ import { ILogger } from "@jmlq/logger";
67
+
68
+ @Injectable()
69
+ export class UsersService {
70
+ constructor(@Inject("LOGGER") private readonly logger: ILogger) {}
71
+
72
+ async createUser(userData: any) {
73
+ try {
74
+ await this.logger.info("Creando usuario", { userData });
75
+ // ... lógica del servicio
76
+ await this.logger.info("Usuario creado exitosamente", {
77
+ userId: result.id,
78
+ });
79
+ return result;
80
+ } catch (error) {
81
+ await this.logger.error("Error al crear usuario", {
82
+ error: error.message,
83
+ userData,
84
+ });
85
+ throw error;
86
+ }
87
+ }
88
+ }
89
+ ```
90
+
91
+ ### Express
92
+
93
+ 1. Configurar logger en app.js
94
+
95
+ ```ts
96
+ // src/logger.ts
97
+ import { LoggerFactory, LogLevel } from "@jmlq/logger";
98
+
99
+ export const createLogger = async () => {
100
+ const datasources = [];
101
+
102
+ // Configurar datasources según variables de entorno
103
+ if (process.env.LOG_FS_ENABLED === "true") {
104
+ const { FileSystemDatasource } = await import("@jmlq/logger-plugin-fs");
105
+ datasources.push(
106
+ new FileSystemDatasource({
107
+ basePath: process.env.LOG_FS_PATH || "./logs",
108
+ })
109
+ );
110
+ }
111
+
112
+ return LoggerFactory.create({
113
+ datasources,
114
+ minLevel: process.env.LOG_LEVEL || LogLevel.INFO,
115
+ redactorOptions: {
116
+ enabled: true,
117
+ deep: true,
118
+ includeDefaults: true,
119
+ patterns: [
120
+ {
121
+ pattern: "\\b\\d{4}-\\d{4}-\\d{4}-\\d{4}\\b",
122
+ replaceWith: "****-****-****-****",
123
+ },
124
+ ],
125
+ },
126
+ });
127
+ };
128
+ ```
129
+
130
+ 2. Middleware de logging
131
+
132
+ ```ts
133
+ // src/middleware/logger.middleware.ts
134
+ import { Request, Response, NextFunction } from "express";
135
+ import { ILogger } from "@jmlq/logger";
136
+
137
+ export const createLoggerMiddleware = (logger: ILogger) => {
138
+ return async (req: Request, res: Response, next: NextFunction) => {
139
+ const startTime = Date.now();
140
+
141
+ await logger.info("Request iniciado", {
142
+ method: req.method,
143
+ url: req.url,
144
+ ip: req.ip,
145
+ userAgent: req.get("User-Agent"),
146
+ });
147
+
148
+ res.on("finish", async () => {
149
+ const duration = Date.now() - startTime;
150
+ const level = res.statusCode >= 400 ? "error" : "info";
151
+
152
+ await logger[level]("Request completado", {
153
+ method: req.method,
154
+ url: req.url,
155
+ statusCode: res.statusCode,
156
+ duration,
157
+ });
158
+ });
159
+
160
+ next();
161
+ };
162
+ };
163
+ ```
164
+
165
+ 3. Usar en la aplicación
166
+
167
+ ```ts
168
+ // src/app.ts
169
+ import express from "express";
170
+ import { createLogger } from "./logger";
171
+ import { createLoggerMiddleware } from "./middleware/logger.middleware";
172
+
173
+ const app = express();
174
+ const logger = await createLogger();
175
+
176
+ app.use(createLoggerMiddleware(logger));
177
+
178
+ app.get("/users/:id", async (req, res) => {
179
+ try {
180
+ await logger.info("Obteniendo usuario", { userId: req.params.id });
181
+ // ... lógica
182
+ res.json(user);
183
+ } catch (error) {
184
+ await logger.error("Error al obtener usuario", {
185
+ userId: req.params.id,
186
+ error: error.message,
187
+ });
188
+ res.status(500).json({ error: "Internal server error" });
189
+ }
190
+ });
191
+ ```
192
+
193
+ ## Configuración de PII (Datos Sensibles)
194
+
195
+ ### Patrones Predefinidos
196
+
197
+ El logger incluye patrones comunes para enmascarar datos sensibles:
198
+
199
+ ```ts
200
+ const logger = LoggerFactory.create({
201
+ datasources,
202
+ redactorOptions: {
203
+ enabled: true,
204
+ deep: true, // Busca en objetos anidados
205
+ includeDefaults: true, // Incluye patrones predefinidos (email, teléfono, etc.)
206
+ },
207
+ });
208
+ ```
209
+
210
+ Patrones Personalizados
211
+
212
+ ```ts
213
+ const logger = LoggerFactory.create({
214
+ datasources,
215
+ redactorOptions: {
216
+ enabled: true,
217
+ deep: true,
218
+ includeDefaults: true,
219
+ patterns: [
220
+ // Tarjetas de crédito
221
+ {
222
+ pattern: "\\b\\d{4}[-\\s]?\\d{4}[-\\s]?\\d{4}[-\\s]?\\d{4}\\b",
223
+ replaceWith: "****-****-****-****",
224
+ },
225
+ // CURP (México)
226
+ {
227
+ pattern: "[A-Z]{4}\\d{6}[HM][A-Z]{5}[A-Z0-9]\\d",
228
+ replaceWith: "****CURP****",
229
+ },
230
+ // Números de cuenta bancaria
231
+ {
232
+ pattern: "\\b\\d{10,20}\\b",
233
+ replaceWith: "****ACCOUNT****",
234
+ },
235
+ // Tokens JWT
236
+ {
237
+ pattern: "eyJ[A-Za-z0-9-_=]+\\.[A-Za-z0-9-_=]+\\.?[A-Za-z0-9-_.+/=]*",
238
+ replaceWith: "****JWT****",
239
+ },
240
+ ],
241
+ },
242
+ });
243
+ ```
244
+
245
+ ## Filtrado de Registros
246
+
247
+ ### Filtros Básicos
248
+
249
+ ```ts
250
+ // Obtener todos los logs de nivel ERROR o superior
251
+ const errors = await logger.getLogs({
252
+ levelMin: LogLevel.ERROR,
253
+ });
254
+
255
+ // Filtrar por rango de fechas
256
+ const yesterday = Date.now() - 24 * 60 * 60 * 1000;
257
+ const recentLogs = await logger.getLogs({
258
+ since: yesterday,
259
+ until: Date.now(),
260
+ });
261
+
262
+ // Búsqueda por texto
263
+ const userLogs = await logger.getLogs({
264
+ query: "usuario",
265
+ limit: 50,
266
+ });
267
+ ```
268
+
269
+ ### Filtros Avanzados
270
+
271
+ ```ts
272
+ // Combinación de filtros
273
+ const criticalRecentErrors = await logger.getLogs({
274
+ levelMin: LogLevel.ERROR,
275
+ since: Date.now() - 2 * 60 * 60 * 1000, // Últimas 2 horas
276
+ query: "database connection",
277
+ limit: 20,
278
+ offset: 0,
279
+ });
280
+
281
+ // Paginación
282
+ const page1 = await logger.getLogs({ limit: 10, offset: 0 });
283
+ const page2 = await logger.getLogs({ limit: 10, offset: 10 });
284
+ ```
285
+
286
+ ## Variables de Entorno
287
+
288
+ ```bash
289
+ # Nivel mínimo de logs
290
+ LOG_LEVEL=info
291
+
292
+ # Filesystem
293
+ LOG_FS_ENABLED=true
294
+ LOG_FS_PATH=./logs
295
+
296
+ # MongoDB (si usas @jmlq/logger-plugin-mongo)
297
+ LOG_MONGO_ENABLED=true
298
+ LOG_MONGO_URL=mongodb://localhost:27017
299
+ LOG_MONGO_DB=logs
300
+
301
+ # PostgreSQL (si usas @jmlq/logger-plugin-postgresql)
302
+ LOG_PG_ENABLED=true
303
+ LOG_PG_HOST=localhost
304
+ LOG_PG_PORT=5432
305
+ LOG_PG_DATABASE=logs
306
+ LOG_PG_USERNAME=logger
307
+ LOG_PG_PASSWORD=secret
308
+ ```
309
+
310
+ ## Ejemplo Completo
311
+
312
+ ```ts
313
+ import { LoggerFactory, LogLevel } from "@jmlq/logger";
314
+
315
+ // Configuración completa
316
+ const logger = await LoggerFactory.create({
317
+ datasources: [
318
+ // Múltiples datasources
319
+ new FileSystemDatasource({ basePath: "./logs" }),
320
+ new MongoDatasource({ url: "mongodb://localhost:27017", dbName: "logs" }),
321
+ ],
322
+ minLevel: LogLevel.DEBUG,
323
+ redactorOptions: {
324
+ enabled: true,
325
+ deep: true,
326
+ includeDefaults: true,
327
+ patterns: [
328
+ {
329
+ pattern: "\\b\\d{4}-\\d{4}-\\d{4}-\\d{4}\\b",
330
+ replaceWith: "****-****-****-****",
331
+ },
332
+ ],
333
+ },
334
+ });
335
+
336
+ // Uso con diferentes niveles
337
+ await logger.debug("Debug info", { userId: 123 });
338
+ await logger.info("User login", { email: "user@example.com" });
339
+ await logger.warn("High latency", { endpoint: "/api/users", duration: 950 });
340
+ await logger.error("Database error", { error: "Connection timeout" });
341
+ await logger.fatal("System crash", { stack: error.stack });
342
+
343
+ // Filtrar y consultar logs
344
+ const recentErrors = await logger.getLogs({
345
+ levelMin: LogLevel.ERROR,
346
+ since: Date.now() - 24 * 60 * 60 * 1000,
347
+ limit: 100,
348
+ });
349
+
350
+ // Limpiar buffers (útil antes de cerrar la aplicación)
351
+ await logger.flush();
352
+ ```
353
+
354
+ ## Plugins Disponibles
355
+
356
+ > - `@jmlq/logger-plugin-fs`: Persistencia en archivos
357
+ > - `@jmlq/logger-plugin-mongo`: Persistencia en MongoDB
358
+ > - `@jmlq/logger-plugin-postgresql`: Persistencia en PostgreSQL
359
+
360
+ Cada plugin se instala por separado según las necesidades de tu aplicación.
361
+
362
+ ## Consideraciones de Rendimiento
363
+
364
+ Los logs se procesan de forma asíncrona
365
+ Múltiples datasources escriben en paralelo
366
+ Usa [flush()](./examples/logger-factory.example.ts) antes de cerrar la aplicación para asegurar que todos los logs se persistan
367
+ Configura límites apropiados en las consultas para evitar sobrecarga de memoria
package/package.json CHANGED
@@ -1,32 +1,42 @@
1
1
  {
2
2
  "name": "@jmlq/logger",
3
- "version": "0.1.0-alpha.7",
4
- "author": "MLahuasi",
5
- "license": "MIT",
3
+ "description": "logger package with clean architecture",
4
+ "version": "0.1.0-alpha.9",
6
5
  "main": "dist/index.js",
7
6
  "types": "dist/index.d.ts",
8
- "files": [
9
- "dist"
10
- ],
11
7
  "scripts": {
12
8
  "build": "tsc -p tsconfig.json",
13
9
  "prepublishOnly": "npm run build",
14
10
  "test": "jest --passWithNoTests",
15
11
  "test:watch": "jest --watch",
16
- "test:cov": "jest --coverage"
12
+ "test:coverage": "jest --coverage",
13
+ "example:help": "tsx examples/index.example.ts help",
14
+ "example:all": "tsx examples/index.example.ts",
15
+ "example:domain-services": "tsx examples/index.example.ts domain-services",
16
+ "example:services": "tsx examples/index.example.ts services",
17
+ "example:use-cases": "tsx examples/index.example.ts use-cases",
18
+ "example:factories": "tsx examples/index.example.ts factories"
17
19
  },
20
+ "keywords": [
21
+ "logger",
22
+ "clean-architecture",
23
+ "typescript"
24
+ ],
25
+ "author": "MLahuasi",
26
+ "license": "MIT",
18
27
  "devDependencies": {
19
- "@swc/core": "^1.13.5",
20
- "@swc/jest": "^0.2.39",
21
- "@types/jest": "^30.0.0",
22
- "@types/node": "^24.3.0",
23
- "jest": "^30.1.3",
24
- "tsx": "^4.20.5",
25
- "typescript": "^5.9.2"
28
+ "@swc/core": "^1.3.95",
29
+ "@swc/jest": "^0.2.29",
30
+ "@types/bcryptjs": "^2.4.5",
31
+ "@types/jest": "^29.5.8",
32
+ "@types/node": "^20.8.10",
33
+ "jest": "^29.7.0",
34
+ "tsx": "^4.1.4",
35
+ "typescript": "^5.2.2"
26
36
  },
27
- "overrides": {
28
- "test-exclude": "^7.0.1",
29
- "glob": "^10.4.5",
30
- "minimatch": "^9.0.5"
31
- }
37
+ "files": [
38
+ "dist",
39
+ "architecture.md",
40
+ "install.md"
41
+ ]
32
42
  }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2024-2025 mlahuasi
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the “Software”), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in
13
- all copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
- THE SOFTWARE.
@@ -1,6 +0,0 @@
1
- import { ILogDatasource } from "../../domain/contracts";
2
- export declare class FlushBuffers {
3
- private readonly ds;
4
- constructor(ds: ILogDatasource);
5
- execute(): Promise<void>;
6
- }