@emartech/json-logger 8.1.0 → 9.0.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/dist/config.js CHANGED
@@ -4,28 +4,28 @@ exports.config = void 0;
4
4
  const levels = {
5
5
  trace: {
6
6
  number: 10,
7
- name: 'TRACE'
7
+ name: 'TRACE',
8
8
  },
9
9
  debug: {
10
10
  number: 20,
11
- name: 'DEBUG'
11
+ name: 'DEBUG',
12
12
  },
13
13
  info: {
14
14
  number: 30,
15
- name: 'INFO'
15
+ name: 'INFO',
16
16
  },
17
17
  warn: {
18
18
  number: 40,
19
- name: 'WARN'
19
+ name: 'WARN',
20
20
  },
21
21
  error: {
22
22
  number: 50,
23
- name: 'ERROR'
23
+ name: 'ERROR',
24
24
  },
25
25
  fatal: {
26
26
  number: 60,
27
- name: 'FATAL'
28
- }
27
+ name: 'FATAL',
28
+ },
29
29
  };
30
30
  const availableLevels = Object.keys(levels);
31
31
  exports.config = { levels, availableLevels };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const enabled_1 = require("./enabled");
4
+ const chai_1 = require("chai");
5
+ describe('isNamespaceAvailable', () => {
6
+ it('should enable when variables only contain one', () => {
7
+ (0, chai_1.expect)((0, enabled_1.isNamespaceEnabled)('mongo', 'mongo')).to.eql(true);
8
+ });
9
+ it('should disable when not in availables', () => {
10
+ (0, chai_1.expect)((0, enabled_1.isNamespaceEnabled)('mongo', 'redis')).to.eql(false);
11
+ });
12
+ it('should enable when part of available and available contains *', () => {
13
+ (0, chai_1.expect)((0, enabled_1.isNamespaceEnabled)('mongo*', 'mongolab')).to.eql(true);
14
+ });
15
+ it('should allow multiple available namespaces', () => {
16
+ const availableNamespaces = 'mongo,redis';
17
+ (0, chai_1.expect)((0, enabled_1.isNamespaceEnabled)(availableNamespaces, 'mongo')).to.eql(true);
18
+ (0, chai_1.expect)((0, enabled_1.isNamespaceEnabled)(availableNamespaces, 'redis')).to.eql(true);
19
+ });
20
+ it('should disable names starting with -', () => {
21
+ (0, chai_1.expect)((0, enabled_1.isNamespaceEnabled)('mongo*,-*lab', 'mongolab')).to.eql(false);
22
+ });
23
+ it('should not work with empty strings', () => {
24
+ (0, chai_1.expect)((0, enabled_1.isNamespaceEnabled)('', '')).to.eql(false);
25
+ });
26
+ it('should enable everything for star', () => {
27
+ (0, chai_1.expect)((0, enabled_1.isNamespaceEnabled)('*', 'mongo')).to.eql(true);
28
+ });
29
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const chai_1 = require("chai");
4
+ const json_1 = require("./json");
5
+ describe('json formatter', () => {
6
+ it('should stringify object to json', () => {
7
+ (0, chai_1.expect)((0, json_1.jsonFormatter)({ name: 'debugger' })).to.eql('{"name":"debugger"}');
8
+ });
9
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const chai_1 = require("chai");
4
+ const logentries_1 = require("./logentries");
5
+ describe('logentries formatter', () => {
6
+ it('should stringify single field to key value pairs', () => {
7
+ (0, chai_1.expect)((0, logentries_1.logentriesFormatter)({ name: 'debugger' })).to.eql('name="debugger"');
8
+ });
9
+ it('should stringify multiple fields separated', () => {
10
+ (0, chai_1.expect)((0, logentries_1.logentriesFormatter)({ name: 'debugger', namespace: 'it' })).to.eql('name="debugger" namespace="it"');
11
+ });
12
+ it('should not print numbers as string', () => {
13
+ (0, chai_1.expect)((0, logentries_1.logentriesFormatter)({ name: 'debugger', duration: 10, percent: 1.5 })).to.eql('name="debugger" duration=10 percent=1.5');
14
+ });
15
+ it('should json stringify nested objects', () => {
16
+ (0, chai_1.expect)((0, logentries_1.logentriesFormatter)({ name: 'debugger', nested: { inner: 10 } })).to.eql('name="debugger" nested="{"inner":10}"');
17
+ });
18
+ });
package/dist/index.js CHANGED
@@ -1,19 +1,20 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createLogger = exports.Timer = exports.Logger = void 0;
3
+ exports.Timer = exports.Logger = void 0;
4
+ exports.createLogger = createLogger;
5
+ const enabled_1 = require("./enabled/enabled");
6
+ const formatter_1 = require("./formatter");
4
7
  const logger_1 = require("./logger/logger");
5
8
  var logger_2 = require("./logger/logger");
6
9
  Object.defineProperty(exports, "Logger", { enumerable: true, get: function () { return logger_2.Logger; } });
7
10
  var timer_1 = require("./timer/timer");
8
11
  Object.defineProperty(exports, "Timer", { enumerable: true, get: function () { return timer_1.Timer; } });
9
- const enabled_1 = require("./enabled/enabled");
10
- const formatter_1 = require("./formatter");
12
+ // eslint-disable-next-line func-style
11
13
  function createLogger(namespace) {
12
14
  return new logger_1.Logger(namespace, (0, enabled_1.isNamespaceEnabled)(createLogger.getNamespaces(), namespace));
13
15
  }
14
- exports.createLogger = createLogger;
15
16
  createLogger.getNamespaces = function () {
16
- return process.env.DEBUG || '';
17
+ return process.env.DEBUG ?? '';
17
18
  };
18
19
  createLogger.configure = function (options) {
19
20
  logger_1.Logger.configure(options);
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const chai_1 = require("chai");
4
+ const index_1 = require("./index");
5
+ describe('createLogger', function () {
6
+ beforeEach(function () {
7
+ process.env.DEBUG = 'mongo';
8
+ });
9
+ afterEach(function () {
10
+ process.env.DEBUG = '';
11
+ });
12
+ it('should return an enabled log instance when env variable is set to same', function () {
13
+ const logger = (0, index_1.createLogger)('mongo');
14
+ (0, chai_1.expect)(logger).to.be.an.instanceOf(index_1.Logger);
15
+ (0, chai_1.expect)(logger.isEnabled()).to.be.true;
16
+ });
17
+ it('should return a disabled log instance when different', function () {
18
+ const logger = (0, index_1.createLogger)('redis');
19
+ (0, chai_1.expect)(logger).to.be.an.instanceOf(index_1.Logger);
20
+ (0, chai_1.expect)(logger.isEnabled()).to.be.false;
21
+ });
22
+ });
@@ -10,6 +10,8 @@ const console_1 = require("../output/console");
10
10
  const lodash_1 = require("lodash");
11
11
  const allowedKeys = ['output', 'formatter', 'transformers', 'outputFormat'];
12
12
  class Logger {
13
+ namespace;
14
+ enabled;
13
15
  constructor(namespace, enabled) {
14
16
  this.namespace = namespace;
15
17
  this.enabled = enabled;
@@ -25,6 +27,12 @@ class Logger {
25
27
  }
26
28
  });
27
29
  }
30
+ static config = {
31
+ formatter: json_1.jsonFormatter,
32
+ output: console_1.consoleOutput,
33
+ transformers: [],
34
+ outputFormat: 'ecs',
35
+ };
28
36
  isEnabled() {
29
37
  return this.enabled;
30
38
  }
@@ -163,9 +171,3 @@ class Logger {
163
171
  }
164
172
  }
165
173
  exports.Logger = Logger;
166
- Logger.config = {
167
- formatter: json_1.jsonFormatter,
168
- output: console_1.consoleOutput,
169
- transformers: [],
170
- outputFormat: 'ecs',
171
- };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,322 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const axios_1 = require("axios");
7
+ const chai_1 = require("chai");
8
+ const sinon_1 = __importDefault(require("sinon"));
9
+ const json_1 = require("../formatter/json");
10
+ const console_1 = require("../output/console");
11
+ const logger_1 = require("./logger");
12
+ describe('Logger', () => {
13
+ let logger;
14
+ let clock;
15
+ let outputStub;
16
+ beforeEach(() => {
17
+ logger = new logger_1.Logger('mongo', true);
18
+ outputStub = sinon_1.default.stub(logger_1.Logger.config, 'output');
19
+ clock = sinon_1.default.useFakeTimers();
20
+ });
21
+ afterEach(() => {
22
+ logger_1.Logger.configure({
23
+ formatter: json_1.jsonFormatter,
24
+ output: console_1.consoleOutput,
25
+ transformers: [],
26
+ outputFormat: 'ecs',
27
+ });
28
+ clock.restore();
29
+ });
30
+ it('should call log info method when enabled (legacy format)', () => {
31
+ logger_1.Logger.configure({ outputFormat: 'legacy' });
32
+ logger.info('wedidit', { details: 'forever' });
33
+ const logArguments = JSON.parse(outputStub.args[0][0]);
34
+ (0, chai_1.expect)(logArguments.name).to.eql('mongo');
35
+ (0, chai_1.expect)(logArguments.action).to.eql('wedidit');
36
+ (0, chai_1.expect)(logArguments.level).to.eql(30);
37
+ (0, chai_1.expect)(logArguments.details).to.eql('forever');
38
+ });
39
+ it('should call log info method when enabled (ecs format)', () => {
40
+ logger_1.Logger.configure({ outputFormat: 'ecs' });
41
+ logger.info('wedidit', { details: 'forever' });
42
+ const logArguments = JSON.parse(outputStub.args[0][0]);
43
+ (0, chai_1.expect)(logArguments.event.action).to.eql('wedidit');
44
+ (0, chai_1.expect)(logArguments.log.logger).to.eql('mongo');
45
+ (0, chai_1.expect)(logArguments.log.level).to.eql(30);
46
+ (0, chai_1.expect)(logArguments.details).to.eql('forever');
47
+ });
48
+ it('should not overwrite fields in ecs base log', () => {
49
+ logger.info('wedidit', { event: { duration: 245 }, log: { ter: 'abc' } });
50
+ const logArguments = JSON.parse(outputStub.args[0][0]);
51
+ (0, chai_1.expect)(logArguments.event.action).to.eql('wedidit');
52
+ (0, chai_1.expect)(logArguments.event.duration).to.eql(245);
53
+ (0, chai_1.expect)(logArguments.log.logger).to.eql('mongo');
54
+ (0, chai_1.expect)(logArguments.log.level).to.eql(30);
55
+ (0, chai_1.expect)(logArguments.log.ter).to.eql('abc');
56
+ });
57
+ it('should be callable without the data object', () => {
58
+ logger.info('wedidit');
59
+ const logArguments = JSON.parse(outputStub.args[0][0]);
60
+ (0, chai_1.expect)(logArguments.event.action).to.eql('wedidit');
61
+ (0, chai_1.expect)(logArguments.log.logger).to.eql('mongo');
62
+ (0, chai_1.expect)(logArguments.log.level).to.eql(30);
63
+ });
64
+ it('should not call log info method when disabled', () => {
65
+ logger = new logger_1.Logger('mongo', false);
66
+ logger.info('hi');
67
+ (0, chai_1.expect)(logger_1.Logger.config.output).not.to.have.been.called;
68
+ });
69
+ it('should not call log info method when disabled (timer)', () => {
70
+ logger = new logger_1.Logger('mongo', false);
71
+ const timer = logger.timer();
72
+ const infoStub = sinon_1.default.stub(logger, 'info');
73
+ clock.tick(100);
74
+ timer.info('hi');
75
+ (0, chai_1.expect)(infoStub).to.have.been.calledWith('hi', { event: { duration: 100 } });
76
+ });
77
+ it('should log error with action (legacy format)', () => {
78
+ logger_1.Logger.configure({ outputFormat: 'legacy' });
79
+ const error = new Error('failed');
80
+ error.data = { test: 'data' };
81
+ logger.fromError('hi', error, { details: 'here' });
82
+ const logArguments = JSON.parse(outputStub.args[0][0]);
83
+ (0, chai_1.expect)(logArguments.name).to.eql('mongo');
84
+ (0, chai_1.expect)(logArguments.action).to.eql('hi');
85
+ (0, chai_1.expect)(logArguments.level).to.eql(50);
86
+ (0, chai_1.expect)(logArguments.details).to.eql('here');
87
+ (0, chai_1.expect)(logArguments.error_name).to.eql(error.name);
88
+ (0, chai_1.expect)(logArguments.error_stack).to.eql(error.stack);
89
+ (0, chai_1.expect)(logArguments.error_message).to.eql(error.message);
90
+ (0, chai_1.expect)(logArguments.error_data).to.eql(JSON.stringify(error.data));
91
+ });
92
+ it('should log error with action (ecs format)', () => {
93
+ logger_1.Logger.configure({ outputFormat: 'ecs' });
94
+ const error = new Error('failed');
95
+ error.data = { test: 'data' };
96
+ logger.fromError('hi', error, { details: 'here' });
97
+ const logArguments = JSON.parse(outputStub.args[0][0]);
98
+ (0, chai_1.expect)(logArguments.event.action).to.eql('hi');
99
+ (0, chai_1.expect)(logArguments.log.logger).to.eql('mongo');
100
+ (0, chai_1.expect)(logArguments.log.level).to.eql(50);
101
+ (0, chai_1.expect)(logArguments.details).to.eql('here');
102
+ (0, chai_1.expect)(logArguments.error.type).to.eql(error.name);
103
+ (0, chai_1.expect)(logArguments.error.stack_trace).to.eql(error.stack);
104
+ (0, chai_1.expect)(logArguments.error.message).to.eql(error.message);
105
+ (0, chai_1.expect)(logArguments.error.context).to.eql(JSON.stringify(error.data));
106
+ });
107
+ it('should not overwrite ecs error fields with custom data', () => {
108
+ const error = new Error('failed');
109
+ error.data = { test: 'data' };
110
+ logger.fromError('hi', error, { error: { bajvan: true } });
111
+ const logArguments = JSON.parse(outputStub.args[0][0]);
112
+ (0, chai_1.expect)(logArguments.error).to.eql({
113
+ type: error.name,
114
+ stack_trace: error.stack,
115
+ message: error.message,
116
+ context: JSON.stringify(error.data),
117
+ bajvan: true,
118
+ });
119
+ });
120
+ it('should log error as warning with action', () => {
121
+ const error = new Error('failed');
122
+ error.data = { test: 'data' };
123
+ logger.warnFromError('hi', error, { details: 'here' });
124
+ const logArguments = JSON.parse(outputStub.args[0][0]);
125
+ (0, chai_1.expect)(logArguments.event.action).to.eql('hi');
126
+ (0, chai_1.expect)(logArguments.log.logger).to.eql('mongo');
127
+ (0, chai_1.expect)(logArguments.log.level).to.eql(40);
128
+ (0, chai_1.expect)(logArguments.details).to.eql('here');
129
+ (0, chai_1.expect)(logArguments.error.type).to.eql(error.name);
130
+ (0, chai_1.expect)(logArguments.error.stack_trace).to.eql(error.stack);
131
+ (0, chai_1.expect)(logArguments.error.message).to.eql(error.message);
132
+ (0, chai_1.expect)(logArguments.error.context).to.eql(JSON.stringify(error.data));
133
+ });
134
+ it('should not log error data when it is undefined', () => {
135
+ const error = new Error('failed');
136
+ logger.warnFromError('hi', error, { details: 'here' });
137
+ const logArguments = JSON.parse(outputStub.args[0][0]);
138
+ (0, chai_1.expect)(logArguments.error).to.not.have.any.keys('context');
139
+ });
140
+ it('should log only 3000 character of data', () => {
141
+ const error = new Error('failed');
142
+ error.data = 'exactlyTen'.repeat(400);
143
+ logger.warnFromError('hi', error, { details: 'here' });
144
+ const logArguments = JSON.parse(outputStub.args[0][0]);
145
+ (0, chai_1.expect)(logArguments.error.context.length).to.eql(3004);
146
+ });
147
+ it('should log request/response details for Axios-like error objects (legacy format)', () => {
148
+ logger_1.Logger.configure({ outputFormat: 'legacy' });
149
+ const error = new axios_1.AxiosError('Request failed with status code 500');
150
+ error.response = {
151
+ status: 500,
152
+ statusText: 'Something horrible happened',
153
+ data: { useful_detail: 'important info' },
154
+ headers: {},
155
+ config: { headers: {} },
156
+ };
157
+ error.config = {
158
+ url: 'http://amazinghost.com/beautiful-path',
159
+ method: 'get',
160
+ headers: {},
161
+ };
162
+ logger.fromError('hi', error, { details: 'here' });
163
+ const logArguments = JSON.parse(outputStub.args[0][0]);
164
+ (0, chai_1.expect)(logArguments.name).to.eql('mongo');
165
+ (0, chai_1.expect)(logArguments.action).to.eql('hi');
166
+ (0, chai_1.expect)(logArguments.level).to.eql(50);
167
+ (0, chai_1.expect)(logArguments.error_name).to.eql(error.name);
168
+ (0, chai_1.expect)(logArguments.error_stack).to.eql(error.stack);
169
+ (0, chai_1.expect)(logArguments.error_message).to.eql(error.message);
170
+ (0, chai_1.expect)(logArguments.request_method).to.eql(error.config.method);
171
+ (0, chai_1.expect)(logArguments.request_url).to.eql(error.config.url);
172
+ (0, chai_1.expect)(logArguments.response_status).to.eql(error.response.status);
173
+ (0, chai_1.expect)(logArguments.response_status_text).to.eql(error.response.statusText);
174
+ (0, chai_1.expect)(logArguments.response_data).to.eql(JSON.stringify(error.response.data));
175
+ });
176
+ it('should log request/response details for Axios-like error objects (ecs format)', () => {
177
+ logger_1.Logger.configure({ outputFormat: 'ecs' });
178
+ const error = new axios_1.AxiosError('Request failed with status code 500');
179
+ error.response = {
180
+ status: 500,
181
+ statusText: 'Something horrible happened',
182
+ data: { useful_detail: 'important info' },
183
+ headers: {},
184
+ config: { headers: {} },
185
+ };
186
+ error.config = {
187
+ url: 'http://amazinghost.com/beautiful-path',
188
+ method: 'get',
189
+ headers: {},
190
+ };
191
+ error.code = 'ECONNREINVENTED';
192
+ logger.fromError('hi', error, { details: 'here' });
193
+ const logArguments = JSON.parse(outputStub.args[0][0]);
194
+ (0, chai_1.expect)(logArguments.log.logger).to.eql('mongo');
195
+ (0, chai_1.expect)(logArguments.event.action).to.eql('hi');
196
+ (0, chai_1.expect)(logArguments.log.level).to.eql(50);
197
+ (0, chai_1.expect)(logArguments.error.code).to.eql(error.code);
198
+ (0, chai_1.expect)(logArguments.error.type).to.eql(error.name);
199
+ (0, chai_1.expect)(logArguments.error.stack_trace).to.eql(error.stack);
200
+ (0, chai_1.expect)(logArguments.error.message).to.eql(error.message);
201
+ (0, chai_1.expect)(logArguments.http.request.method).to.eql(error.config?.method);
202
+ (0, chai_1.expect)(logArguments.url.full).to.eql(error.config?.url);
203
+ (0, chai_1.expect)(logArguments.http.response.status_code).to.eql(error.response?.status);
204
+ (0, chai_1.expect)(logArguments.http.response.body.content).to.eql(JSON.stringify(error.response?.data));
205
+ });
206
+ describe('#customError', () => {
207
+ it('should log error as the given severity with action', () => {
208
+ const error = new Error('failed');
209
+ error.data = { test: 'data' };
210
+ logger.customError('info', 'hi', error, { details: 'here' });
211
+ const logArguments = JSON.parse(outputStub.args[0][0]);
212
+ (0, chai_1.expect)(logArguments.event.action).to.eql('hi');
213
+ (0, chai_1.expect)(logArguments.log.logger).to.eql('mongo');
214
+ (0, chai_1.expect)(logArguments.log.level).to.eql(30);
215
+ (0, chai_1.expect)(logArguments.details).to.eql('here');
216
+ (0, chai_1.expect)(logArguments.error.type).to.eql(error.name);
217
+ (0, chai_1.expect)(logArguments.error.stack_trace).to.eql(error.stack);
218
+ (0, chai_1.expect)(logArguments.error.message).to.eql(error.message);
219
+ (0, chai_1.expect)(logArguments.error.context).to.eql(JSON.stringify(error.data));
220
+ });
221
+ it('should not log error data when it is undefined', () => {
222
+ const error = new Error('failed');
223
+ logger.customError('warn', 'hi', error, { details: 'here' });
224
+ const logArguments = JSON.parse(outputStub.args[0][0]);
225
+ (0, chai_1.expect)(logArguments.error).to.not.have.any.keys('context');
226
+ });
227
+ it('should not log error code when it is undefined in the AxiosError object', () => {
228
+ const error = new axios_1.AxiosError('failed');
229
+ logger.customError('warn', 'hi', error, { details: 'here' });
230
+ const logArguments = JSON.parse(outputStub.args[0][0]);
231
+ (0, chai_1.expect)(logArguments.error).to.not.have.any.keys('code');
232
+ });
233
+ it('should log only 3000 character of data', () => {
234
+ const error = new Error('failed');
235
+ error.data = 'exactlyTen'.repeat(400);
236
+ logger.customError('error', 'hi', error, { details: 'here' });
237
+ const logArguments = JSON.parse(outputStub.args[0][0]);
238
+ (0, chai_1.expect)(logArguments.error.context.length).to.eql(3004);
239
+ });
240
+ describe('when not an Error instance is passed as error', () => {
241
+ [
242
+ { type: 'custom object', value: {} },
243
+ { type: 'string', value: 'error' },
244
+ { type: 'null', value: null },
245
+ { type: 'number', value: 12 },
246
+ { type: 'bool', value: true },
247
+ ].forEach(({ type, value }) => {
248
+ it(`should not throw error when ${type} is passed as error`, () => {
249
+ (0, chai_1.expect)(() => logger.customError('error', 'hi', value, { details: 'here' })).to.not.throw();
250
+ });
251
+ });
252
+ it('should log error properties from custom error object', () => {
253
+ const errorObject = { name: 'Error', message: 'My custom error', stack: 'Stack', data: { value: 1 } };
254
+ logger.customError('error', 'hi', errorObject, { details: 'here' });
255
+ const logArguments = JSON.parse(outputStub.args[0][0]);
256
+ (0, chai_1.expect)(logArguments.error.type).to.eql(errorObject.name);
257
+ (0, chai_1.expect)(logArguments.error.stack_trace).to.eql(errorObject.stack);
258
+ (0, chai_1.expect)(logArguments.error.message).to.eql(errorObject.message);
259
+ (0, chai_1.expect)(logArguments.error.context).to.eql(JSON.stringify(errorObject.data));
260
+ });
261
+ it('should not log additional or missing error properties from custom error object', () => {
262
+ const errorObject = { color: 'color', value: 'value' };
263
+ // @ts-expect-error TS2345
264
+ logger.customError('error', 'hi', errorObject, { details: 'here' });
265
+ const logArguments = JSON.parse(outputStub.args[0][0]);
266
+ (0, chai_1.expect)(logArguments).to.not.have.any.keys('error_name', 'error_stack', 'error_message', 'error_data');
267
+ (0, chai_1.expect)(logArguments).to.not.have.any.keys('color', 'value');
268
+ });
269
+ });
270
+ });
271
+ describe('#configure', () => {
272
+ it('should change format method', () => {
273
+ const formattedOutput = '{"my":"method"}';
274
+ const formatterStub = sinon_1.default.stub();
275
+ formatterStub.returns(formattedOutput);
276
+ logger_1.Logger.configure({
277
+ formatter: formatterStub,
278
+ });
279
+ logger.info('hi');
280
+ (0, chai_1.expect)(formatterStub).to.have.been.called;
281
+ (0, chai_1.expect)(logger_1.Logger.config.output).to.have.been.calledWith(formattedOutput);
282
+ });
283
+ it('should change output method', () => {
284
+ const outputStub = sinon_1.default.stub();
285
+ logger_1.Logger.configure({
286
+ output: outputStub,
287
+ });
288
+ logger.info('hi');
289
+ (0, chai_1.expect)(outputStub).to.have.been.called;
290
+ });
291
+ it('should change output format', () => {
292
+ logger_1.Logger.configure({
293
+ outputFormat: 'legacy',
294
+ });
295
+ logger.info('hi');
296
+ const logArguments = JSON.parse(outputStub.args[0][0]);
297
+ (0, chai_1.expect)(logArguments.action).to.eql('hi');
298
+ (0, chai_1.expect)(logArguments.event).to.be.undefined;
299
+ });
300
+ it('should throw error on invalid config', () => {
301
+ try {
302
+ logger_1.Logger.configure({
303
+ // @ts-expect-error TS2345
304
+ invalid: true,
305
+ });
306
+ throw new Error('should throw');
307
+ }
308
+ catch (e) {
309
+ (0, chai_1.expect)(e.message).to.eql('Only the following keys are allowed: output,formatter,transformers,outputFormat');
310
+ }
311
+ });
312
+ it('should modify logged data based on transformers', () => {
313
+ logger_1.Logger.configure({
314
+ transformers: [(log) => Object.assign({ debug: true }, log)],
315
+ });
316
+ logger.info('hi');
317
+ const logArguments = JSON.parse(outputStub.args[0][0]);
318
+ (0, chai_1.expect)(logArguments.event.action).to.eql('hi');
319
+ (0, chai_1.expect)(logArguments.debug).to.eql(true);
320
+ });
321
+ });
322
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const sinon_1 = __importDefault(require("sinon"));
7
+ const chai_1 = __importDefault(require("chai"));
8
+ const sinon_chai_1 = __importDefault(require("sinon-chai"));
9
+ chai_1.default.use(sinon_chai_1.default);
10
+ afterEach(() => {
11
+ sinon_1.default.restore();
12
+ });
@@ -4,6 +4,8 @@ exports.Timer = void 0;
4
4
  const logger_1 = require("../logger/logger");
5
5
  const lodash_1 = require("lodash");
6
6
  class Timer {
7
+ start;
8
+ logger;
7
9
  constructor(logger) {
8
10
  this.logger = logger;
9
11
  this.start = new Date().getTime();
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const chai_1 = require("chai");
4
+ const sinon_1 = require("sinon");
5
+ const logger_1 = require("../logger/logger");
6
+ const timer_1 = require("./timer");
7
+ describe('Timer', () => {
8
+ let clock;
9
+ beforeEach(() => {
10
+ clock = (0, sinon_1.useFakeTimers)();
11
+ });
12
+ afterEach(() => {
13
+ clock.restore();
14
+ logger_1.Logger.configure({ outputFormat: 'ecs' });
15
+ });
16
+ describe('legacy format', () => {
17
+ beforeEach(() => {
18
+ logger_1.Logger.configure({ outputFormat: 'legacy' });
19
+ });
20
+ it('should log elapsed time (legacy format)', () => {
21
+ const logger = new logger_1.Logger('test', false);
22
+ const infoStub = (0, sinon_1.stub)(logger, 'info');
23
+ const timer = new timer_1.Timer(logger);
24
+ clock.tick(100);
25
+ timer.info('time', { customer_id: 10 });
26
+ (0, chai_1.expect)(infoStub).to.have.been.calledWith('time', { customer_id: 10, duration: 100 });
27
+ });
28
+ it('should log elapsed time with error', () => {
29
+ const logger = new logger_1.Logger('test', false);
30
+ const errorStub = (0, sinon_1.stub)(logger, 'fromError');
31
+ const timer = new timer_1.Timer(logger);
32
+ const error = new Error('intended');
33
+ clock.tick(100);
34
+ timer.fromError('time', error, { customer_id: 10 });
35
+ (0, chai_1.expect)(errorStub).to.have.been.calledWith('time', error, { customer_id: 10, duration: 100 });
36
+ });
37
+ it('should log elapsed time with error', () => {
38
+ const logger = new logger_1.Logger('test', false);
39
+ const errorStub = (0, sinon_1.stub)(logger, 'warnFromError');
40
+ const timer = new timer_1.Timer(logger);
41
+ const error = new Error('intended');
42
+ clock.tick(100);
43
+ timer.warnFromError('time', error, { customer_id: 10 });
44
+ (0, chai_1.expect)(errorStub).to.have.been.calledWith('time', error, { customer_id: 10, duration: 100 });
45
+ });
46
+ });
47
+ describe('ecs format', () => {
48
+ it('should log elapsed time (legacy format)', () => {
49
+ const logger = new logger_1.Logger('test', false);
50
+ const infoStub = (0, sinon_1.stub)(logger, 'info');
51
+ const timer = new timer_1.Timer(logger);
52
+ clock.tick(100);
53
+ timer.info('time', { customer_id: 10 });
54
+ (0, chai_1.expect)(infoStub).to.have.been.calledWith('time', { customer_id: 10, event: { duration: 100 } });
55
+ });
56
+ it('should log elapsed time with error', () => {
57
+ const logger = new logger_1.Logger('test', false);
58
+ const errorStub = (0, sinon_1.stub)(logger, 'fromError');
59
+ const timer = new timer_1.Timer(logger);
60
+ const error = new Error('intended');
61
+ clock.tick(100);
62
+ timer.fromError('time', error, { customer_id: 10 });
63
+ (0, chai_1.expect)(errorStub).to.have.been.calledWith('time', error, { customer_id: 10, event: { duration: 100 } });
64
+ });
65
+ it('should log elapsed time with error', () => {
66
+ const logger = new logger_1.Logger('test', false);
67
+ const errorStub = (0, sinon_1.stub)(logger, 'warnFromError');
68
+ const timer = new timer_1.Timer(logger);
69
+ const error = new Error('intended');
70
+ clock.tick(100);
71
+ timer.warnFromError('time', error, { customer_id: 10 });
72
+ (0, chai_1.expect)(errorStub).to.have.been.calledWith('time', error, { customer_id: 10, event: { duration: 100 } });
73
+ });
74
+ it('should not overwrite ecs fields', () => {
75
+ const logger = new logger_1.Logger('test', false);
76
+ const logStub = (0, sinon_1.stub)(logger, 'warn');
77
+ const timer = new timer_1.Timer(logger);
78
+ clock.tick(100);
79
+ timer.warn('time', { event: { majomkutya: 1 } });
80
+ (0, chai_1.expect)(logStub).to.have.been.calledWith('time', { event: { duration: 100, majomkutya: 1 } });
81
+ });
82
+ });
83
+ });
package/package.json CHANGED
@@ -2,11 +2,15 @@
2
2
  "name": "@emartech/json-logger",
3
3
  "description": "Tiny and fast json logger with namespace support",
4
4
  "main": "dist/index.js",
5
+ "files": [
6
+ "dist",
7
+ "!**.spec.*"
8
+ ],
5
9
  "scripts": {
6
10
  "test": "mocha --require ts-node/register --extension ts ./src --recursive",
7
11
  "test:watch": "mocha --require ts-node/register --extension ts ./src --recursive --watch",
8
- "lint": "eslint ./src/**/*.ts",
9
- "lint:fix": "eslint ./src/**/*.ts --fix",
12
+ "lint": "eslint .",
13
+ "lint:fix": "eslint . --fix",
10
14
  "build": "rm -rf dist && tsc --project ./tsconfig.json",
11
15
  "release": "CI=true semantic-release",
12
16
  "example-js": "DEBUG=* node examples/index-js.js",
@@ -32,35 +36,35 @@
32
36
  "json"
33
37
  ],
34
38
  "engines": {
35
- "node": ">=14"
39
+ "node": ">=20"
36
40
  },
37
41
  "dependencies": {
38
42
  "lodash": "^4.17.21"
39
43
  },
40
44
  "devDependencies": {
41
- "@types/chai": "4.3.3",
42
- "@types/lodash": "4.14.198",
43
- "@types/mocha": "10.0.0",
44
- "@types/node": "18.7.23",
45
- "@types/sinon": "10.0.13",
46
- "@types/sinon-chai": "3.2.8",
47
- "@typescript-eslint/eslint-plugin": "5.38.1",
48
- "@typescript-eslint/parser": "5.38.1",
49
- "axios": "0.30.0",
50
- "chai": "4.3.6",
51
- "eslint": "8.24.0",
45
+ "@types/chai": "4.3.20",
46
+ "@types/lodash": "4.17.20",
47
+ "@types/mocha": "10.0.10",
48
+ "@types/node": "20.19.22",
49
+ "@types/sinon": "17.0.4",
50
+ "@types/sinon-chai": "3.2.12",
51
+ "@typescript-eslint/eslint-plugin": "6.21.0",
52
+ "@typescript-eslint/parser": "6.21.0",
53
+ "axios": "1.11.0",
54
+ "chai": "4.5.0",
55
+ "eslint": "8.57.1",
52
56
  "eslint-config-emarsys": "5.1.0",
53
- "eslint-config-prettier": "8.5.0",
54
- "eslint-plugin-no-only-tests": "3.0.0",
55
- "eslint-plugin-prettier": "4.2.1",
56
- "eslint-plugin-security": "1.5.0",
57
- "mocha": "10.0.0",
58
- "prettier": "2.7.1",
57
+ "eslint-config-prettier": "10.1.8",
58
+ "eslint-plugin-no-only-tests": "3.3.0",
59
+ "eslint-plugin-prettier": "5.5.4",
60
+ "eslint-plugin-security": "2.1.1",
61
+ "mocha": "10.8.2",
62
+ "prettier": "3.6.2",
59
63
  "semantic-release": "19.0.5",
60
- "sinon": "14.0.0",
64
+ "sinon": "21.0.0",
61
65
  "sinon-chai": "3.7.0",
62
- "ts-node": "10.9.1",
63
- "typescript": "4.8.4"
66
+ "ts-node": "10.9.2",
67
+ "typescript": "5.9.3"
64
68
  },
65
- "version": "8.1.0"
69
+ "version": "9.0.0"
66
70
  }
package/.nvmrc DELETED
@@ -1 +0,0 @@
1
- 14.20.0
package/renovate.json DELETED
@@ -1,34 +0,0 @@
1
- {
2
- "$schema": "https://docs.renovatebot.com/renovate-schema.json",
3
- "extends": [
4
- "config:best-practices",
5
- ":enableVulnerabilityAlerts",
6
- ":pinOnlyDevDependencies",
7
- ":semanticCommits",
8
- ":separateMultipleMajorReleases",
9
- "group:allNonMajor"
10
- ],
11
- "dependencyDashboardLabels": ["dependencies"],
12
- "labels": ["dependencies"],
13
- "lockFileMaintenance": {
14
- "enabled": true,
15
- "schedule": ["on the 1-7 day on Sunday"]
16
- },
17
- "packageRules": [
18
- {
19
- "groupName": "axios",
20
- "matchPackageNames": ["axios"],
21
- "matchUpdateTypes": ["minor"]
22
- },
23
- {
24
- "groupName": "typescript",
25
- "matchPackageNames": ["typescript"],
26
- "matchUpdateTypes": ["minor"]
27
- },
28
- {
29
- "matchPackageNames": ["axios", "typescript"],
30
- "separateMultipleMinor": true
31
- }
32
- ],
33
- "schedule": ["on the 1-7 day on Sunday"]
34
- }
package/repo-info.json DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "is_in_production": true,
3
- "is_scannable": true,
4
- "is_critical": false,
5
- "contact": "guild-javascript@emarsys.com",
6
- "hosted": null
7
- }
package/tsconfig.json DELETED
@@ -1,105 +0,0 @@
1
- {
2
- "exclude": ["dist", "node_modules"],
3
- "include": ["src/**/*.ts"],
4
- "compilerOptions": {
5
- /* Visit https://aka.ms/tsconfig to read more about this file */
6
-
7
- /* Projects */
8
- // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
9
- // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
10
- // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
11
- // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
12
- // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
13
- // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
14
-
15
- /* Language and Environment */
16
- "target": "es2020", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
17
- // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
18
- // "jsx": "preserve", /* Specify what JSX code is generated. */
19
- "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
20
- "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
21
- // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
22
- // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
23
- // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
24
- // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
25
- // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
26
- // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
27
- // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
28
-
29
- /* Modules */
30
- "module": "commonjs", /* Specify what module code is generated. */
31
- "rootDir": "./src", /* Specify the root folder within your source files. */
32
- // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
33
- // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
34
- // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
35
- // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
36
- // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
37
- // "types": [], /* Specify type package names to be included without being referenced in a source file. */
38
- // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
39
- // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
40
- // "resolveJsonModule": true, /* Enable importing .json files. */
41
- // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
42
-
43
- /* JavaScript Support */
44
- "allowJs": false, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
45
- // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
46
- // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
47
-
48
- /* Emit */
49
- "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
50
- // "declarationMap": true, /* Create sourcemaps for d.ts files. */
51
- // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
52
- // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
53
- // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
54
- "outDir": "./dist", /* Specify an output folder for all emitted files. */
55
- // "removeComments": true, /* Disable emitting comments. */
56
- "noEmit": false, /* Disable emitting files from a compilation. */
57
- // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
58
- // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
59
- // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
60
- // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
61
- // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
62
- // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
63
- // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
64
- // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
65
- // "newLine": "crlf", /* Set the newline character for emitting files. */
66
- // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
67
- // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
68
- // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
69
- // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
70
- // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
71
- // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
72
-
73
- /* Interop Constraints */
74
- // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
75
- // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
76
- "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
77
- // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
78
- "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
79
-
80
- /* Type Checking */
81
- "strict": true, /* Enable all strict type-checking options. */
82
- // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
83
- // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
84
- // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
85
- // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
86
- // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
87
- // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
88
- // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
89
- // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
90
- // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
91
- // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
92
- // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
93
- // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
94
- // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
95
- // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
96
- // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
97
- // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
98
- // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
99
- // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
100
-
101
- /* Completeness */
102
- // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
103
- "skipLibCheck": true /* Skip type checking all .d.ts files. */
104
- }
105
- }