@naturalcycles/js-lib 14.64.0 → 14.65.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.
@@ -1,3 +1,4 @@
1
+ import { CommonLogger } from '..';
1
2
  /**
2
3
  * $r - result
3
4
  *
@@ -36,6 +37,10 @@ export interface LogMethodOptions {
36
37
  * Overrides `logResult`.
37
38
  */
38
39
  logResultFn?: LogResultFn;
40
+ /**
41
+ * Defaults to `console`
42
+ */
43
+ logger?: CommonLogger;
39
44
  }
40
45
  /**
41
46
  * Console-logs when method had started, when it finished, time taken and if error happened.
@@ -21,11 +21,11 @@ const decorator_util_1 = require("./decorator.util");
21
21
  function _LogMethod(opt = {}) {
22
22
  return (target, key, descriptor) => {
23
23
  if (typeof descriptor.value !== 'function') {
24
- throw new TypeError('@LogMillis can be applied only to methods');
24
+ throw new TypeError('@_LogMethod can be applied only to methods');
25
25
  }
26
26
  const originalFn = descriptor.value;
27
27
  const keyStr = String(key);
28
- const { avg, noLogArgs, logStart, logResult, noLogResultLength } = opt;
28
+ const { avg, noLogArgs, logStart, logResult, noLogResultLength, logger = console } = opt;
29
29
  let { logResultFn } = opt;
30
30
  if (!logResultFn) {
31
31
  if (logResult) {
@@ -46,29 +46,29 @@ function _LogMethod(opt = {}) {
46
46
  const argsStr = (0, decorator_util_1._getArgsSignature)(args, noLogArgs);
47
47
  const callSignature = `${methodSignature}(${argsStr}) #${++count}`;
48
48
  if (logStart)
49
- console.log(`>> ${callSignature}`);
49
+ logger.log(`>> ${callSignature}`);
50
50
  try {
51
51
  const res = originalFn.apply(ctx, args);
52
52
  if (res && typeof res.then === 'function') {
53
53
  // Result is a Promise, will wait for resolution or rejection
54
54
  return res
55
55
  .then((r) => {
56
- logFinished(callSignature, started, sma, logResultFn, r);
56
+ logFinished(logger, callSignature, started, sma, logResultFn, r);
57
57
  return r;
58
58
  })
59
59
  .catch((err) => {
60
- logFinished(callSignature, started, sma, logResultFn, undefined, err);
60
+ logFinished(logger, callSignature, started, sma, logResultFn, undefined, err);
61
61
  return Promise.reject(err);
62
62
  });
63
63
  }
64
64
  else {
65
65
  // not a Promise
66
- logFinished(callSignature, started, sma, logResultFn, res);
66
+ logFinished(logger, callSignature, started, sma, logResultFn, res);
67
67
  return res;
68
68
  }
69
69
  }
70
70
  catch (err) {
71
- logFinished(callSignature, started, sma, logResultFn, undefined, err);
71
+ logFinished(logger, callSignature, started, sma, logResultFn, undefined, err);
72
72
  throw err; // rethrow
73
73
  }
74
74
  };
@@ -76,7 +76,7 @@ function _LogMethod(opt = {}) {
76
76
  };
77
77
  }
78
78
  exports._LogMethod = _LogMethod;
79
- function logFinished(callSignature, started, sma, logResultFn, res, err) {
79
+ function logFinished(logger, callSignature, started, sma, logResultFn, res, err) {
80
80
  const millis = Date.now() - started;
81
81
  const t = ['<<', callSignature, 'took', (0, time_util_1._ms)(millis)];
82
82
  if (sma) {
@@ -88,5 +88,5 @@ function logFinished(callSignature, started, sma, logResultFn, res, err) {
88
88
  else if (logResultFn) {
89
89
  t.push(...logResultFn(res));
90
90
  }
91
- console.log(t.filter(Boolean).join(' '));
91
+ logger.log(t.filter(Boolean).join(' '));
92
92
  }
@@ -1,11 +1,22 @@
1
+ import { CommonLogger } from '../log/commonLogger';
1
2
  import { MemoCache } from './memo.util';
2
3
  export interface MemoOptions {
4
+ /**
5
+ * Default to false
6
+ */
3
7
  logHit?: boolean;
8
+ /**
9
+ * Default to false
10
+ */
4
11
  logMiss?: boolean;
5
12
  /**
6
13
  * Skip logging method arguments.
7
14
  */
8
15
  noLogArgs?: boolean;
16
+ /**
17
+ * Default to `console`
18
+ */
19
+ logger?: CommonLogger;
9
20
  /**
10
21
  * Provide a custom implementation of MemoCache.
11
22
  * Function that creates an instance of `MemoCache`.
@@ -33,7 +33,7 @@ const _Memo = (opt = {}) => (target, key, descriptor) => {
33
33
  // UPD: tests show that normal Map also doesn't leak (to be tested further)
34
34
  // Normal Map is needed to allow .dropCache()
35
35
  const cache = new Map();
36
- const { logHit, logMiss, noLogArgs, cacheFactory = () => new memo_util_1.MapMemoCache(), cacheKeyFn = memo_util_1.jsonMemoSerializer, noCacheRejected, noCacheResolved, } = opt;
36
+ const { logHit = false, logMiss = false, noLogArgs = false, logger = console, cacheFactory = () => new memo_util_1.MapMemoCache(), cacheKeyFn = memo_util_1.jsonMemoSerializer, noCacheRejected = false, noCacheResolved = false, } = opt;
37
37
  const awaitPromise = Boolean(noCacheRejected || noCacheResolved);
38
38
  const keyStr = String(key);
39
39
  const methodSignature = (0, decorator_util_1._getTargetMethodSignature)(target, keyStr);
@@ -45,7 +45,7 @@ const _Memo = (opt = {}) => (target, key, descriptor) => {
45
45
  }
46
46
  else if (cache.get(ctx).has(cacheKey)) {
47
47
  if (logHit) {
48
- console.log(`${(0, decorator_util_1._getMethodSignature)(ctx, keyStr)}(${(0, decorator_util_1._getArgsSignature)(args, noLogArgs)}) @memoInstance hit`);
48
+ logger.log(`${(0, decorator_util_1._getMethodSignature)(ctx, keyStr)}(${(0, decorator_util_1._getArgsSignature)(args, noLogArgs)}) @_Memo hit`);
49
49
  }
50
50
  const res = cache.get(ctx).get(cacheKey);
51
51
  if (awaitPromise) {
@@ -62,7 +62,7 @@ const _Memo = (opt = {}) => (target, key, descriptor) => {
62
62
  .then(res => {
63
63
  // console.log('RESOLVED', res)
64
64
  if (logMiss) {
65
- console.log(`${(0, decorator_util_1._getMethodSignature)(ctx, keyStr)}(${(0, decorator_util_1._getArgsSignature)(args, noLogArgs)}) @memo miss resolved (${(0, time_util_1._since)(started)})`);
65
+ logger.log(`${(0, decorator_util_1._getMethodSignature)(ctx, keyStr)}(${(0, decorator_util_1._getArgsSignature)(args, noLogArgs)}) @_Memo miss resolved (${(0, time_util_1._since)(started)})`);
66
66
  }
67
67
  if (!noCacheResolved) {
68
68
  cache.get(ctx).set(cacheKey, res);
@@ -72,7 +72,7 @@ const _Memo = (opt = {}) => (target, key, descriptor) => {
72
72
  .catch(err => {
73
73
  // console.log('REJECTED', err)
74
74
  if (logMiss) {
75
- console.log(`${(0, decorator_util_1._getMethodSignature)(ctx, keyStr)}(${(0, decorator_util_1._getArgsSignature)(args, noLogArgs)}) @memo miss rejected (${(0, time_util_1._since)(started)})`);
75
+ logger.log(`${(0, decorator_util_1._getMethodSignature)(ctx, keyStr)}(${(0, decorator_util_1._getArgsSignature)(args, noLogArgs)}) @_Memo miss rejected (${(0, time_util_1._since)(started)})`);
76
76
  }
77
77
  if (!noCacheRejected) {
78
78
  // We put it to cache as raw Error, not Promise.reject(err)
@@ -85,14 +85,14 @@ const _Memo = (opt = {}) => (target, key, descriptor) => {
85
85
  }
86
86
  else {
87
87
  if (logMiss) {
88
- console.log(`${(0, decorator_util_1._getMethodSignature)(ctx, keyStr)}(${(0, decorator_util_1._getArgsSignature)(args, noLogArgs)}) @memo miss (${(0, time_util_1._since)(started)})`);
88
+ logger.log(`${(0, decorator_util_1._getMethodSignature)(ctx, keyStr)}(${(0, decorator_util_1._getArgsSignature)(args, noLogArgs)}) @_Memo miss (${(0, time_util_1._since)(started)})`);
89
89
  }
90
90
  cache.get(ctx).set(cacheKey, res);
91
91
  return res;
92
92
  }
93
93
  };
94
94
  descriptor.value.dropCache = () => {
95
- console.log(`${methodSignature} @memo.dropCache()`);
95
+ logger.log(`${methodSignature} @_Memo.dropCache()`);
96
96
  cache.forEach(memoCache => memoCache.clear());
97
97
  cache.clear();
98
98
  };
@@ -5,7 +5,7 @@ const time_util_1 = require("../time/time.util");
5
5
  const decorator_util_1 = require("./decorator.util");
6
6
  const memo_util_1 = require("./memo.util");
7
7
  function _memoFn(fn, opt = {}) {
8
- const { logHit, logMiss, noLogArgs, noCacheRejected, noCacheResolved, cacheFactory = () => new memo_util_1.MapMemoCache(), cacheKeyFn = memo_util_1.jsonMemoSerializer, } = opt;
8
+ const { logHit = false, logMiss = false, noLogArgs = false, logger = console, noCacheRejected = false, noCacheResolved = false, cacheFactory = () => new memo_util_1.MapMemoCache(), cacheKeyFn = memo_util_1.jsonMemoSerializer, } = opt;
9
9
  const cache = cacheFactory();
10
10
  const awaitPromise = Boolean(noCacheRejected || noCacheResolved);
11
11
  const fnName = fn.name;
@@ -14,7 +14,7 @@ function _memoFn(fn, opt = {}) {
14
14
  const cacheKey = cacheKeyFn(args);
15
15
  if (cache.has(cacheKey)) {
16
16
  if (logHit) {
17
- console.log(`${fnName}(${(0, decorator_util_1._getArgsSignature)(args, noLogArgs)}) memoFn hit`);
17
+ logger.log(`${fnName}(${(0, decorator_util_1._getArgsSignature)(args, noLogArgs)}) memoFn hit`);
18
18
  }
19
19
  const res = cache.get(cacheKey);
20
20
  if (awaitPromise) {
@@ -31,7 +31,7 @@ function _memoFn(fn, opt = {}) {
31
31
  .then(res => {
32
32
  // console.log('RESOLVED', res)
33
33
  if (logMiss) {
34
- console.log(`${fnName}(${(0, decorator_util_1._getArgsSignature)(args, noLogArgs)}) memoFn miss resolved (${(0, time_util_1._since)(started)})`);
34
+ logger.log(`${fnName}(${(0, decorator_util_1._getArgsSignature)(args, noLogArgs)}) memoFn miss resolved (${(0, time_util_1._since)(started)})`);
35
35
  }
36
36
  if (!noCacheResolved) {
37
37
  cache.set(cacheKey, res);
@@ -41,7 +41,7 @@ function _memoFn(fn, opt = {}) {
41
41
  .catch(err => {
42
42
  // console.log('REJECTED', err)
43
43
  if (logMiss) {
44
- console.log(`${fnName}(${(0, decorator_util_1._getArgsSignature)(args, noLogArgs)}) memoFn miss rejected (${(0, time_util_1._since)(started)})`);
44
+ logger.log(`${fnName}(${(0, decorator_util_1._getArgsSignature)(args, noLogArgs)}) memoFn miss rejected (${(0, time_util_1._since)(started)})`);
45
45
  }
46
46
  if (!noCacheRejected) {
47
47
  // We put it to cache as raw Error, not Promise.reject(err)
@@ -54,7 +54,7 @@ function _memoFn(fn, opt = {}) {
54
54
  }
55
55
  else {
56
56
  if (logMiss) {
57
- console.log(`${fnName}(${(0, decorator_util_1._getArgsSignature)(args, noLogArgs)}) @memo miss (${(0, time_util_1._since)(started)})`);
57
+ logger.log(`${fnName}(${(0, decorator_util_1._getArgsSignature)(args, noLogArgs)}) memoFn miss (${(0, time_util_1._since)(started)})`);
58
58
  }
59
59
  cache.set(cacheKey, res);
60
60
  return res;
@@ -1,7 +1,9 @@
1
+ import { CommonLogger } from '../log/commonLogger';
1
2
  export interface MemoOpts {
2
3
  logHit?: boolean;
3
4
  logMiss?: boolean;
4
5
  noLogArgs?: boolean;
6
+ logger?: CommonLogger;
5
7
  }
6
8
  /**
7
9
  * Memoizes the method of the class, so it caches the output and returns the cached version if the "key"
@@ -6,12 +6,6 @@
6
6
  // https://community.risingstack.com/the-worlds-fastest-javascript-memoization-library/
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
8
  exports.memoSimple = void 0;
9
- /*
10
- Optimized for 0 arguments (using SingleValueCache).
11
- Optimized for 1 primitive argument (skips JSON.stringify).
12
- Otherwise resorts to JSON.stringify.
13
- Benchmark shows similar perf for ObjectCache and MapCache.
14
- */
15
9
  const decorator_util_1 = require("./decorator.util");
16
10
  const memo_util_1 = require("./memo.util");
17
11
  // memoSimple decorator is NOT exported. Only used in benchmarks currently
@@ -43,7 +37,7 @@ const memoSimple = (opt = {}) => (target, key, descriptor) => {
43
37
  }
44
38
  */
45
39
  const cache = new memo_util_1.MapMemoCache();
46
- const { logHit, logMiss, noLogArgs } = opt;
40
+ const { logHit, logMiss, noLogArgs, logger = console } = opt;
47
41
  const keyStr = String(key);
48
42
  const methodSignature = (0, decorator_util_1._getTargetMethodSignature)(target, keyStr);
49
43
  descriptor.value = function (...args) {
@@ -51,20 +45,20 @@ const memoSimple = (opt = {}) => (target, key, descriptor) => {
51
45
  const cacheKey = (0, memo_util_1.jsonMemoSerializer)(args);
52
46
  if (cache.has(cacheKey)) {
53
47
  if (logHit) {
54
- console.log(`${methodSignature}(${(0, decorator_util_1._getArgsSignature)(args, noLogArgs)}) @memo hit`);
48
+ logger.log(`${methodSignature}(${(0, decorator_util_1._getArgsSignature)(args, noLogArgs)}) @memo hit`);
55
49
  }
56
50
  return cache.get(cacheKey);
57
51
  }
58
52
  const d = Date.now();
59
53
  const res = originalFn.apply(ctx, args);
60
54
  if (logMiss) {
61
- console.log(`${methodSignature}(${(0, decorator_util_1._getArgsSignature)(args, noLogArgs)}) @memo miss (${Date.now() - d} ms)`);
55
+ logger.log(`${methodSignature}(${(0, decorator_util_1._getArgsSignature)(args, noLogArgs)}) @memo miss (${Date.now() - d} ms)`);
62
56
  }
63
57
  cache.set(cacheKey, res);
64
58
  return res;
65
59
  };
66
60
  descriptor.value.dropCache = () => {
67
- console.log(`${methodSignature} @memo.dropCache()`);
61
+ logger.log(`${methodSignature} @memo.dropCache()`);
68
62
  cache.clear();
69
63
  };
70
64
  return descriptor;
@@ -41,7 +41,6 @@ export interface HttpErrorData extends ErrorData {
41
41
  *
42
42
  * GET /api/some-endpoint
43
43
  */
44
- endpoint?: string;
45
44
  /**
46
45
  * Set to true when the error was thrown after response headers were sent.
47
46
  */
@@ -1,3 +1,4 @@
1
+ import { CommonLogger } from '../index';
1
2
  import { AnyFunction } from '../types';
2
3
  export interface TryCatchOptions {
3
4
  /**
@@ -13,6 +14,10 @@ export interface TryCatchOptions {
13
14
  * @default true
14
15
  */
15
16
  logError?: boolean;
17
+ /**
18
+ * Default to `console`
19
+ */
20
+ logger?: CommonLogger;
16
21
  }
17
22
  /**
18
23
  * Decorates a function with "try/catch", so it'll never reject/throw.
@@ -11,23 +11,20 @@ const index_1 = require("../index");
11
11
  * @experimental
12
12
  */
13
13
  function _tryCatch(fn, opt = {}) {
14
- const { onError, logError, logSuccess } = {
15
- logError: true,
16
- ...opt,
17
- };
14
+ const { onError, logError = true, logSuccess = false, logger = console } = opt;
18
15
  const fname = fn.name || 'anonymous';
19
16
  return async function (...args) {
20
17
  const started = Date.now();
21
18
  try {
22
19
  const r = await fn.apply(this, args);
23
20
  if (logSuccess) {
24
- console.log(`tryCatch.${fname} succeeded in ${(0, index_1._since)(started)}`);
21
+ logger.log(`tryCatch.${fname} succeeded in ${(0, index_1._since)(started)}`);
25
22
  }
26
23
  return r;
27
24
  }
28
25
  catch (err) {
29
26
  if (logError) {
30
- console.warn(`tryCatch.${fname} error in ${(0, index_1._since)(started)}:\n${(0, index_1._stringifyAny)(err, {
27
+ logger.warn(`tryCatch.${fname} error in ${(0, index_1._since)(started)}:\n${(0, index_1._stringifyAny)(err, {
31
28
  includeErrorData: true,
32
29
  })}`);
33
30
  }
@@ -1,3 +1,4 @@
1
+ import { CommonLogger } from '..';
1
2
  export interface PRetryOptions {
2
3
  /**
3
4
  * How many attempts to try.
@@ -52,6 +53,10 @@ export interface PRetryOptions {
52
53
  * @default false
53
54
  */
54
55
  logNone?: boolean;
56
+ /**
57
+ * Default to `console`
58
+ */
59
+ logger?: CommonLogger;
55
60
  }
56
61
  /**
57
62
  * Returns a Function (!), enhanced with retry capabilities.
@@ -8,7 +8,7 @@ const __1 = require("..");
8
8
  */
9
9
  // eslint-disable-next-line @typescript-eslint/ban-types
10
10
  function pRetry(fn, opt = {}) {
11
- const { maxAttempts = 4, delay: initialDelay = 1000, delayMultiplier = 2, predicate } = opt;
11
+ const { maxAttempts = 4, delay: initialDelay = 1000, delayMultiplier = 2, predicate, logger = console, } = opt;
12
12
  let { logFirstAttempt = false, logRetries = true, logFailures = false, logSuccess = false } = opt;
13
13
  if (opt.logAll) {
14
14
  logFirstAttempt = logRetries = logFailures = true;
@@ -26,17 +26,17 @@ function pRetry(fn, opt = {}) {
26
26
  try {
27
27
  attempt++;
28
28
  if ((attempt === 1 && logFirstAttempt) || (attempt > 1 && logRetries)) {
29
- console.log(`${fname} attempt #${attempt}...`);
29
+ logger.log(`${fname} attempt #${attempt}...`);
30
30
  }
31
31
  const r = await fn.apply(this, args);
32
32
  if (logSuccess) {
33
- console.log(`${fname} attempt #${attempt} succeeded in ${(0, __1._since)(started)}`);
33
+ logger.log(`${fname} attempt #${attempt} succeeded in ${(0, __1._since)(started)}`);
34
34
  }
35
35
  resolve(r);
36
36
  }
37
37
  catch (err) {
38
38
  if (logFailures) {
39
- console.warn(`${fname} attempt #${attempt} error in ${(0, __1._since)(started)}:\n${(0, __1._stringifyAny)(err, {
39
+ logger.warn(`${fname} attempt #${attempt} error in ${(0, __1._since)(started)}:\n${(0, __1._stringifyAny)(err, {
40
40
  includeErrorData: true,
41
41
  })}`);
42
42
  }
@@ -18,11 +18,11 @@ import { _getArgsSignature, _getMethodSignature } from './decorator.util';
18
18
  export function _LogMethod(opt = {}) {
19
19
  return (target, key, descriptor) => {
20
20
  if (typeof descriptor.value !== 'function') {
21
- throw new TypeError('@LogMillis can be applied only to methods');
21
+ throw new TypeError('@_LogMethod can be applied only to methods');
22
22
  }
23
23
  const originalFn = descriptor.value;
24
24
  const keyStr = String(key);
25
- const { avg, noLogArgs, logStart, logResult, noLogResultLength } = opt;
25
+ const { avg, noLogArgs, logStart, logResult, noLogResultLength, logger = console } = opt;
26
26
  let { logResultFn } = opt;
27
27
  if (!logResultFn) {
28
28
  if (logResult) {
@@ -43,36 +43,36 @@ export function _LogMethod(opt = {}) {
43
43
  const argsStr = _getArgsSignature(args, noLogArgs);
44
44
  const callSignature = `${methodSignature}(${argsStr}) #${++count}`;
45
45
  if (logStart)
46
- console.log(`>> ${callSignature}`);
46
+ logger.log(`>> ${callSignature}`);
47
47
  try {
48
48
  const res = originalFn.apply(ctx, args);
49
49
  if (res && typeof res.then === 'function') {
50
50
  // Result is a Promise, will wait for resolution or rejection
51
51
  return res
52
52
  .then((r) => {
53
- logFinished(callSignature, started, sma, logResultFn, r);
53
+ logFinished(logger, callSignature, started, sma, logResultFn, r);
54
54
  return r;
55
55
  })
56
56
  .catch((err) => {
57
- logFinished(callSignature, started, sma, logResultFn, undefined, err);
57
+ logFinished(logger, callSignature, started, sma, logResultFn, undefined, err);
58
58
  return Promise.reject(err);
59
59
  });
60
60
  }
61
61
  else {
62
62
  // not a Promise
63
- logFinished(callSignature, started, sma, logResultFn, res);
63
+ logFinished(logger, callSignature, started, sma, logResultFn, res);
64
64
  return res;
65
65
  }
66
66
  }
67
67
  catch (err) {
68
- logFinished(callSignature, started, sma, logResultFn, undefined, err);
68
+ logFinished(logger, callSignature, started, sma, logResultFn, undefined, err);
69
69
  throw err; // rethrow
70
70
  }
71
71
  };
72
72
  return descriptor;
73
73
  };
74
74
  }
75
- function logFinished(callSignature, started, sma, logResultFn, res, err) {
75
+ function logFinished(logger, callSignature, started, sma, logResultFn, res, err) {
76
76
  const millis = Date.now() - started;
77
77
  const t = ['<<', callSignature, 'took', _ms(millis)];
78
78
  if (sma) {
@@ -84,5 +84,5 @@ function logFinished(callSignature, started, sma, logResultFn, res, err) {
84
84
  else if (logResultFn) {
85
85
  t.push(...logResultFn(res));
86
86
  }
87
- console.log(t.filter(Boolean).join(' '));
87
+ logger.log(t.filter(Boolean).join(' '));
88
88
  }
@@ -30,7 +30,7 @@ export const _Memo = (opt = {}) => (target, key, descriptor) => {
30
30
  // UPD: tests show that normal Map also doesn't leak (to be tested further)
31
31
  // Normal Map is needed to allow .dropCache()
32
32
  const cache = new Map();
33
- const { logHit, logMiss, noLogArgs, cacheFactory = () => new MapMemoCache(), cacheKeyFn = jsonMemoSerializer, noCacheRejected, noCacheResolved, } = opt;
33
+ const { logHit = false, logMiss = false, noLogArgs = false, logger = console, cacheFactory = () => new MapMemoCache(), cacheKeyFn = jsonMemoSerializer, noCacheRejected = false, noCacheResolved = false, } = opt;
34
34
  const awaitPromise = Boolean(noCacheRejected || noCacheResolved);
35
35
  const keyStr = String(key);
36
36
  const methodSignature = _getTargetMethodSignature(target, keyStr);
@@ -42,7 +42,7 @@ export const _Memo = (opt = {}) => (target, key, descriptor) => {
42
42
  }
43
43
  else if (cache.get(ctx).has(cacheKey)) {
44
44
  if (logHit) {
45
- console.log(`${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(args, noLogArgs)}) @memoInstance hit`);
45
+ logger.log(`${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(args, noLogArgs)}) @_Memo hit`);
46
46
  }
47
47
  const res = cache.get(ctx).get(cacheKey);
48
48
  if (awaitPromise) {
@@ -59,7 +59,7 @@ export const _Memo = (opt = {}) => (target, key, descriptor) => {
59
59
  .then(res => {
60
60
  // console.log('RESOLVED', res)
61
61
  if (logMiss) {
62
- console.log(`${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(args, noLogArgs)}) @memo miss resolved (${_since(started)})`);
62
+ logger.log(`${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(args, noLogArgs)}) @_Memo miss resolved (${_since(started)})`);
63
63
  }
64
64
  if (!noCacheResolved) {
65
65
  cache.get(ctx).set(cacheKey, res);
@@ -69,7 +69,7 @@ export const _Memo = (opt = {}) => (target, key, descriptor) => {
69
69
  .catch(err => {
70
70
  // console.log('REJECTED', err)
71
71
  if (logMiss) {
72
- console.log(`${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(args, noLogArgs)}) @memo miss rejected (${_since(started)})`);
72
+ logger.log(`${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(args, noLogArgs)}) @_Memo miss rejected (${_since(started)})`);
73
73
  }
74
74
  if (!noCacheRejected) {
75
75
  // We put it to cache as raw Error, not Promise.reject(err)
@@ -82,14 +82,14 @@ export const _Memo = (opt = {}) => (target, key, descriptor) => {
82
82
  }
83
83
  else {
84
84
  if (logMiss) {
85
- console.log(`${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(args, noLogArgs)}) @memo miss (${_since(started)})`);
85
+ logger.log(`${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(args, noLogArgs)}) @_Memo miss (${_since(started)})`);
86
86
  }
87
87
  cache.get(ctx).set(cacheKey, res);
88
88
  return res;
89
89
  }
90
90
  };
91
91
  descriptor.value.dropCache = () => {
92
- console.log(`${methodSignature} @memo.dropCache()`);
92
+ logger.log(`${methodSignature} @_Memo.dropCache()`);
93
93
  cache.forEach(memoCache => memoCache.clear());
94
94
  cache.clear();
95
95
  };
@@ -2,7 +2,7 @@ import { _since } from '../time/time.util';
2
2
  import { _getArgsSignature } from './decorator.util';
3
3
  import { jsonMemoSerializer, MapMemoCache } from './memo.util';
4
4
  export function _memoFn(fn, opt = {}) {
5
- const { logHit, logMiss, noLogArgs, noCacheRejected, noCacheResolved, cacheFactory = () => new MapMemoCache(), cacheKeyFn = jsonMemoSerializer, } = opt;
5
+ const { logHit = false, logMiss = false, noLogArgs = false, logger = console, noCacheRejected = false, noCacheResolved = false, cacheFactory = () => new MapMemoCache(), cacheKeyFn = jsonMemoSerializer, } = opt;
6
6
  const cache = cacheFactory();
7
7
  const awaitPromise = Boolean(noCacheRejected || noCacheResolved);
8
8
  const fnName = fn.name;
@@ -11,7 +11,7 @@ export function _memoFn(fn, opt = {}) {
11
11
  const cacheKey = cacheKeyFn(args);
12
12
  if (cache.has(cacheKey)) {
13
13
  if (logHit) {
14
- console.log(`${fnName}(${_getArgsSignature(args, noLogArgs)}) memoFn hit`);
14
+ logger.log(`${fnName}(${_getArgsSignature(args, noLogArgs)}) memoFn hit`);
15
15
  }
16
16
  const res = cache.get(cacheKey);
17
17
  if (awaitPromise) {
@@ -28,7 +28,7 @@ export function _memoFn(fn, opt = {}) {
28
28
  .then(res => {
29
29
  // console.log('RESOLVED', res)
30
30
  if (logMiss) {
31
- console.log(`${fnName}(${_getArgsSignature(args, noLogArgs)}) memoFn miss resolved (${_since(started)})`);
31
+ logger.log(`${fnName}(${_getArgsSignature(args, noLogArgs)}) memoFn miss resolved (${_since(started)})`);
32
32
  }
33
33
  if (!noCacheResolved) {
34
34
  cache.set(cacheKey, res);
@@ -38,7 +38,7 @@ export function _memoFn(fn, opt = {}) {
38
38
  .catch(err => {
39
39
  // console.log('REJECTED', err)
40
40
  if (logMiss) {
41
- console.log(`${fnName}(${_getArgsSignature(args, noLogArgs)}) memoFn miss rejected (${_since(started)})`);
41
+ logger.log(`${fnName}(${_getArgsSignature(args, noLogArgs)}) memoFn miss rejected (${_since(started)})`);
42
42
  }
43
43
  if (!noCacheRejected) {
44
44
  // We put it to cache as raw Error, not Promise.reject(err)
@@ -51,7 +51,7 @@ export function _memoFn(fn, opt = {}) {
51
51
  }
52
52
  else {
53
53
  if (logMiss) {
54
- console.log(`${fnName}(${_getArgsSignature(args, noLogArgs)}) @memo miss (${_since(started)})`);
54
+ logger.log(`${fnName}(${_getArgsSignature(args, noLogArgs)}) memoFn miss (${_since(started)})`);
55
55
  }
56
56
  cache.set(cacheKey, res);
57
57
  return res;
@@ -3,12 +3,6 @@
3
3
  // http://decodize.com/blog/2012/08/27/javascript-memoization-caching-results-for-better-performance/
4
4
  // http://inlehmansterms.net/2015/03/01/javascript-memoization/
5
5
  // https://community.risingstack.com/the-worlds-fastest-javascript-memoization-library/
6
- /*
7
- Optimized for 0 arguments (using SingleValueCache).
8
- Optimized for 1 primitive argument (skips JSON.stringify).
9
- Otherwise resorts to JSON.stringify.
10
- Benchmark shows similar perf for ObjectCache and MapCache.
11
- */
12
6
  import { _getArgsSignature, _getTargetMethodSignature } from './decorator.util';
13
7
  import { jsonMemoSerializer, MapMemoCache } from './memo.util';
14
8
  // memoSimple decorator is NOT exported. Only used in benchmarks currently
@@ -40,7 +34,7 @@ export const memoSimple = (opt = {}) => (target, key, descriptor) => {
40
34
  }
41
35
  */
42
36
  const cache = new MapMemoCache();
43
- const { logHit, logMiss, noLogArgs } = opt;
37
+ const { logHit, logMiss, noLogArgs, logger = console } = opt;
44
38
  const keyStr = String(key);
45
39
  const methodSignature = _getTargetMethodSignature(target, keyStr);
46
40
  descriptor.value = function (...args) {
@@ -48,20 +42,20 @@ export const memoSimple = (opt = {}) => (target, key, descriptor) => {
48
42
  const cacheKey = jsonMemoSerializer(args);
49
43
  if (cache.has(cacheKey)) {
50
44
  if (logHit) {
51
- console.log(`${methodSignature}(${_getArgsSignature(args, noLogArgs)}) @memo hit`);
45
+ logger.log(`${methodSignature}(${_getArgsSignature(args, noLogArgs)}) @memo hit`);
52
46
  }
53
47
  return cache.get(cacheKey);
54
48
  }
55
49
  const d = Date.now();
56
50
  const res = originalFn.apply(ctx, args);
57
51
  if (logMiss) {
58
- console.log(`${methodSignature}(${_getArgsSignature(args, noLogArgs)}) @memo miss (${Date.now() - d} ms)`);
52
+ logger.log(`${methodSignature}(${_getArgsSignature(args, noLogArgs)}) @memo miss (${Date.now() - d} ms)`);
59
53
  }
60
54
  cache.set(cacheKey, res);
61
55
  return res;
62
56
  };
63
57
  descriptor.value.dropCache = () => {
64
- console.log(`${methodSignature} @memo.dropCache()`);
58
+ logger.log(`${methodSignature} @memo.dropCache()`);
65
59
  cache.clear();
66
60
  };
67
61
  return descriptor;
@@ -8,20 +8,20 @@ import { _since, _stringifyAny } from '../index';
8
8
  * @experimental
9
9
  */
10
10
  export function _tryCatch(fn, opt = {}) {
11
- const { onError, logError, logSuccess } = Object.assign({ logError: true }, opt);
11
+ const { onError, logError = true, logSuccess = false, logger = console } = opt;
12
12
  const fname = fn.name || 'anonymous';
13
13
  return async function (...args) {
14
14
  const started = Date.now();
15
15
  try {
16
16
  const r = await fn.apply(this, args);
17
17
  if (logSuccess) {
18
- console.log(`tryCatch.${fname} succeeded in ${_since(started)}`);
18
+ logger.log(`tryCatch.${fname} succeeded in ${_since(started)}`);
19
19
  }
20
20
  return r;
21
21
  }
22
22
  catch (err) {
23
23
  if (logError) {
24
- console.warn(`tryCatch.${fname} error in ${_since(started)}:\n${_stringifyAny(err, {
24
+ logger.warn(`tryCatch.${fname} error in ${_since(started)}:\n${_stringifyAny(err, {
25
25
  includeErrorData: true,
26
26
  })}`);
27
27
  }
@@ -5,7 +5,7 @@ import { _since, _stringifyAny } from '..';
5
5
  */
6
6
  // eslint-disable-next-line @typescript-eslint/ban-types
7
7
  export function pRetry(fn, opt = {}) {
8
- const { maxAttempts = 4, delay: initialDelay = 1000, delayMultiplier = 2, predicate } = opt;
8
+ const { maxAttempts = 4, delay: initialDelay = 1000, delayMultiplier = 2, predicate, logger = console, } = opt;
9
9
  let { logFirstAttempt = false, logRetries = true, logFailures = false, logSuccess = false } = opt;
10
10
  if (opt.logAll) {
11
11
  logFirstAttempt = logRetries = logFailures = true;
@@ -23,17 +23,17 @@ export function pRetry(fn, opt = {}) {
23
23
  try {
24
24
  attempt++;
25
25
  if ((attempt === 1 && logFirstAttempt) || (attempt > 1 && logRetries)) {
26
- console.log(`${fname} attempt #${attempt}...`);
26
+ logger.log(`${fname} attempt #${attempt}...`);
27
27
  }
28
28
  const r = await fn.apply(this, args);
29
29
  if (logSuccess) {
30
- console.log(`${fname} attempt #${attempt} succeeded in ${_since(started)}`);
30
+ logger.log(`${fname} attempt #${attempt} succeeded in ${_since(started)}`);
31
31
  }
32
32
  resolve(r);
33
33
  }
34
34
  catch (err) {
35
35
  if (logFailures) {
36
- console.warn(`${fname} attempt #${attempt} error in ${_since(started)}:\n${_stringifyAny(err, {
36
+ logger.warn(`${fname} attempt #${attempt} error in ${_since(started)}:\n${_stringifyAny(err, {
37
37
  includeErrorData: true,
38
38
  })}`);
39
39
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@naturalcycles/js-lib",
3
- "version": "14.64.0",
3
+ "version": "14.65.0",
4
4
  "scripts": {
5
5
  "prepare": "husky install",
6
6
  "build-prod": "build-prod-esm-cjs",
@@ -1,4 +1,4 @@
1
- import { SimpleMovingAverage, _stringifyAny } from '..'
1
+ import { SimpleMovingAverage, _stringifyAny, CommonLogger } from '..'
2
2
  import { _ms } from '../time/time.util'
3
3
  import { _getArgsSignature, _getMethodSignature } from './decorator.util'
4
4
 
@@ -46,6 +46,11 @@ export interface LogMethodOptions {
46
46
  * Overrides `logResult`.
47
47
  */
48
48
  logResultFn?: LogResultFn
49
+
50
+ /**
51
+ * Defaults to `console`
52
+ */
53
+ logger?: CommonLogger
49
54
  }
50
55
 
51
56
  /**
@@ -65,13 +70,13 @@ export interface LogMethodOptions {
65
70
  export function _LogMethod(opt: LogMethodOptions = {}): MethodDecorator {
66
71
  return (target, key, descriptor) => {
67
72
  if (typeof descriptor.value !== 'function') {
68
- throw new TypeError('@LogMillis can be applied only to methods')
73
+ throw new TypeError('@_LogMethod can be applied only to methods')
69
74
  }
70
75
 
71
76
  const originalFn = descriptor.value
72
77
  const keyStr = String(key)
73
78
 
74
- const { avg, noLogArgs, logStart, logResult, noLogResultLength } = opt
79
+ const { avg, noLogArgs, logStart, logResult, noLogResultLength, logger = console } = opt
75
80
  let { logResultFn } = opt
76
81
  if (!logResultFn) {
77
82
  if (logResult) {
@@ -93,7 +98,7 @@ export function _LogMethod(opt: LogMethodOptions = {}): MethodDecorator {
93
98
  const methodSignature = _getMethodSignature(ctx, keyStr)
94
99
  const argsStr = _getArgsSignature(args, noLogArgs)
95
100
  const callSignature = `${methodSignature}(${argsStr}) #${++count}`
96
- if (logStart) console.log(`>> ${callSignature}`)
101
+ if (logStart) logger.log(`>> ${callSignature}`)
97
102
 
98
103
  try {
99
104
  const res = originalFn.apply(ctx, args)
@@ -102,20 +107,20 @@ export function _LogMethod(opt: LogMethodOptions = {}): MethodDecorator {
102
107
  // Result is a Promise, will wait for resolution or rejection
103
108
  return res
104
109
  .then((r: any) => {
105
- logFinished(callSignature, started, sma, logResultFn, r)
110
+ logFinished(logger, callSignature, started, sma, logResultFn, r)
106
111
  return r
107
112
  })
108
113
  .catch((err: any) => {
109
- logFinished(callSignature, started, sma, logResultFn, undefined, err)
114
+ logFinished(logger, callSignature, started, sma, logResultFn, undefined, err)
110
115
  return Promise.reject(err)
111
116
  })
112
117
  } else {
113
118
  // not a Promise
114
- logFinished(callSignature, started, sma, logResultFn, res)
119
+ logFinished(logger, callSignature, started, sma, logResultFn, res)
115
120
  return res
116
121
  }
117
122
  } catch (err) {
118
- logFinished(callSignature, started, sma, logResultFn, undefined, err)
123
+ logFinished(logger, callSignature, started, sma, logResultFn, undefined, err)
119
124
  throw err // rethrow
120
125
  }
121
126
  } as any
@@ -125,6 +130,7 @@ export function _LogMethod(opt: LogMethodOptions = {}): MethodDecorator {
125
130
  }
126
131
 
127
132
  function logFinished(
133
+ logger: CommonLogger,
128
134
  callSignature: string,
129
135
  started: number,
130
136
  sma?: SimpleMovingAverage,
@@ -146,5 +152,5 @@ function logFinished(
146
152
  t.push(...logResultFn(res))
147
153
  }
148
154
 
149
- console.log(t.filter(Boolean).join(' '))
155
+ logger.log(t.filter(Boolean).join(' '))
150
156
  }
@@ -4,13 +4,20 @@
4
4
  // http://inlehmansterms.net/2015/03/01/javascript-memoization/
5
5
  // https://community.risingstack.com/the-worlds-fastest-javascript-memoization-library/
6
6
 
7
+ import { CommonLogger } from '../log/commonLogger'
7
8
  import { _since } from '../time/time.util'
8
9
  import { AnyObject } from '../types'
9
10
  import { _getArgsSignature, _getMethodSignature, _getTargetMethodSignature } from './decorator.util'
10
11
  import { jsonMemoSerializer, MapMemoCache, MemoCache } from './memo.util'
11
12
 
12
13
  export interface MemoOptions {
14
+ /**
15
+ * Default to false
16
+ */
13
17
  logHit?: boolean
18
+ /**
19
+ * Default to false
20
+ */
14
21
  logMiss?: boolean
15
22
 
16
23
  /**
@@ -18,6 +25,11 @@ export interface MemoOptions {
18
25
  */
19
26
  noLogArgs?: boolean
20
27
 
28
+ /**
29
+ * Default to `console`
30
+ */
31
+ logger?: CommonLogger
32
+
21
33
  /**
22
34
  * Provide a custom implementation of MemoCache.
23
35
  * Function that creates an instance of `MemoCache`.
@@ -73,13 +85,14 @@ export const _Memo =
73
85
  const cache = new Map<AnyObject, MemoCache>()
74
86
 
75
87
  const {
76
- logHit,
77
- logMiss,
78
- noLogArgs,
88
+ logHit = false,
89
+ logMiss = false,
90
+ noLogArgs = false,
91
+ logger = console,
79
92
  cacheFactory = () => new MapMemoCache(),
80
93
  cacheKeyFn = jsonMemoSerializer,
81
- noCacheRejected,
82
- noCacheResolved,
94
+ noCacheRejected = false,
95
+ noCacheResolved = false,
83
96
  } = opt
84
97
 
85
98
  const awaitPromise = Boolean(noCacheRejected || noCacheResolved)
@@ -95,11 +108,8 @@ export const _Memo =
95
108
  cache.set(ctx, cacheFactory())
96
109
  } else if (cache.get(ctx)!.has(cacheKey)) {
97
110
  if (logHit) {
98
- console.log(
99
- `${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(
100
- args,
101
- noLogArgs,
102
- )}) @memoInstance hit`,
111
+ logger.log(
112
+ `${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(args, noLogArgs)}) @_Memo hit`,
103
113
  )
104
114
  }
105
115
 
@@ -121,11 +131,11 @@ export const _Memo =
121
131
  .then(res => {
122
132
  // console.log('RESOLVED', res)
123
133
  if (logMiss) {
124
- console.log(
134
+ logger.log(
125
135
  `${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(
126
136
  args,
127
137
  noLogArgs,
128
- )}) @memo miss resolved (${_since(started)})`,
138
+ )}) @_Memo miss resolved (${_since(started)})`,
129
139
  )
130
140
  }
131
141
 
@@ -138,11 +148,11 @@ export const _Memo =
138
148
  .catch(err => {
139
149
  // console.log('REJECTED', err)
140
150
  if (logMiss) {
141
- console.log(
151
+ logger.log(
142
152
  `${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(
143
153
  args,
144
154
  noLogArgs,
145
- )}) @memo miss rejected (${_since(started)})`,
155
+ )}) @_Memo miss rejected (${_since(started)})`,
146
156
  )
147
157
  }
148
158
 
@@ -157,11 +167,11 @@ export const _Memo =
157
167
  })
158
168
  } else {
159
169
  if (logMiss) {
160
- console.log(
170
+ logger.log(
161
171
  `${_getMethodSignature(ctx, keyStr)}(${_getArgsSignature(
162
172
  args,
163
173
  noLogArgs,
164
- )}) @memo miss (${_since(started)})`,
174
+ )}) @_Memo miss (${_since(started)})`,
165
175
  )
166
176
  }
167
177
 
@@ -170,7 +180,7 @@ export const _Memo =
170
180
  }
171
181
  } as any
172
182
  ;(descriptor.value as any).dropCache = () => {
173
- console.log(`${methodSignature} @memo.dropCache()`)
183
+ logger.log(`${methodSignature} @_Memo.dropCache()`)
174
184
  cache.forEach(memoCache => memoCache.clear())
175
185
  cache.clear()
176
186
  }
@@ -12,11 +12,12 @@ export function _memoFn<T extends (...args: any[]) => any>(
12
12
  opt: MemoOptions = {},
13
13
  ): T & MemoizedFunction {
14
14
  const {
15
- logHit,
16
- logMiss,
17
- noLogArgs,
18
- noCacheRejected,
19
- noCacheResolved,
15
+ logHit = false,
16
+ logMiss = false,
17
+ noLogArgs = false,
18
+ logger = console,
19
+ noCacheRejected = false,
20
+ noCacheResolved = false,
20
21
  cacheFactory = () => new MapMemoCache(),
21
22
  cacheKeyFn = jsonMemoSerializer,
22
23
  } = opt
@@ -31,7 +32,7 @@ export function _memoFn<T extends (...args: any[]) => any>(
31
32
 
32
33
  if (cache.has(cacheKey)) {
33
34
  if (logHit) {
34
- console.log(`${fnName}(${_getArgsSignature(args, noLogArgs)}) memoFn hit`)
35
+ logger.log(`${fnName}(${_getArgsSignature(args, noLogArgs)}) memoFn hit`)
35
36
  }
36
37
 
37
38
  const res = cache.get(cacheKey)
@@ -52,7 +53,7 @@ export function _memoFn<T extends (...args: any[]) => any>(
52
53
  .then(res => {
53
54
  // console.log('RESOLVED', res)
54
55
  if (logMiss) {
55
- console.log(
56
+ logger.log(
56
57
  `${fnName}(${_getArgsSignature(args, noLogArgs)}) memoFn miss resolved (${_since(
57
58
  started,
58
59
  )})`,
@@ -68,7 +69,7 @@ export function _memoFn<T extends (...args: any[]) => any>(
68
69
  .catch(err => {
69
70
  // console.log('REJECTED', err)
70
71
  if (logMiss) {
71
- console.log(
72
+ logger.log(
72
73
  `${fnName}(${_getArgsSignature(args, noLogArgs)}) memoFn miss rejected (${_since(
73
74
  started,
74
75
  )})`,
@@ -86,8 +87,8 @@ export function _memoFn<T extends (...args: any[]) => any>(
86
87
  }) as any
87
88
  } else {
88
89
  if (logMiss) {
89
- console.log(
90
- `${fnName}(${_getArgsSignature(args, noLogArgs)}) @memo miss (${_since(started)})`,
90
+ logger.log(
91
+ `${fnName}(${_getArgsSignature(args, noLogArgs)}) memoFn miss (${_since(started)})`,
91
92
  )
92
93
  }
93
94
 
@@ -11,6 +11,7 @@ Otherwise resorts to JSON.stringify.
11
11
  Benchmark shows similar perf for ObjectCache and MapCache.
12
12
  */
13
13
 
14
+ import { CommonLogger } from '../log/commonLogger'
14
15
  import { _getArgsSignature, _getTargetMethodSignature } from './decorator.util'
15
16
  import { jsonMemoSerializer, MapMemoCache, MemoCache } from './memo.util'
16
17
 
@@ -18,6 +19,7 @@ export interface MemoOpts {
18
19
  logHit?: boolean
19
20
  logMiss?: boolean
20
21
  noLogArgs?: boolean
22
+ logger?: CommonLogger
21
23
  }
22
24
 
23
25
  // memoSimple decorator is NOT exported. Only used in benchmarks currently
@@ -55,7 +57,7 @@ export const memoSimple =
55
57
  */
56
58
  const cache: MemoCache = new MapMemoCache()
57
59
 
58
- const { logHit, logMiss, noLogArgs } = opt
60
+ const { logHit, logMiss, noLogArgs, logger = console } = opt
59
61
  const keyStr = String(key)
60
62
  const methodSignature = _getTargetMethodSignature(target, keyStr)
61
63
 
@@ -65,7 +67,7 @@ export const memoSimple =
65
67
 
66
68
  if (cache.has(cacheKey)) {
67
69
  if (logHit) {
68
- console.log(`${methodSignature}(${_getArgsSignature(args, noLogArgs)}) @memo hit`)
70
+ logger.log(`${methodSignature}(${_getArgsSignature(args, noLogArgs)}) @memo hit`)
69
71
  }
70
72
  return cache.get(cacheKey)
71
73
  }
@@ -75,7 +77,7 @@ export const memoSimple =
75
77
  const res: any = originalFn.apply(ctx, args)
76
78
 
77
79
  if (logMiss) {
78
- console.log(
80
+ logger.log(
79
81
  `${methodSignature}(${_getArgsSignature(args, noLogArgs)}) @memo miss (${
80
82
  Date.now() - d
81
83
  } ms)`,
@@ -87,7 +89,7 @@ export const memoSimple =
87
89
  return res
88
90
  } as any
89
91
  ;(descriptor.value as any).dropCache = () => {
90
- console.log(`${methodSignature} @memo.dropCache()`)
92
+ logger.log(`${methodSignature} @memo.dropCache()`)
91
93
  cache.clear()
92
94
  }
93
95
 
@@ -48,7 +48,7 @@ export interface HttpErrorData extends ErrorData {
48
48
  *
49
49
  * GET /api/some-endpoint
50
50
  */
51
- endpoint?: string
51
+ // endpoint?: string
52
52
 
53
53
  /**
54
54
  * Set to true when the error was thrown after response headers were sent.
@@ -1,4 +1,4 @@
1
- import { _since, _stringifyAny } from '../index'
1
+ import { _since, _stringifyAny, CommonLogger } from '../index'
2
2
  import { AnyFunction } from '../types'
3
3
 
4
4
  export interface TryCatchOptions {
@@ -17,6 +17,11 @@ export interface TryCatchOptions {
17
17
  * @default true
18
18
  */
19
19
  logError?: boolean
20
+
21
+ /**
22
+ * Default to `console`
23
+ */
24
+ logger?: CommonLogger
20
25
  }
21
26
 
22
27
  /**
@@ -28,10 +33,7 @@ export interface TryCatchOptions {
28
33
  * @experimental
29
34
  */
30
35
  export function _tryCatch<T extends AnyFunction>(fn: T, opt: TryCatchOptions = {}): T {
31
- const { onError, logError, logSuccess } = {
32
- logError: true,
33
- ...opt,
34
- }
36
+ const { onError, logError = true, logSuccess = false, logger = console } = opt
35
37
 
36
38
  const fname = fn.name || 'anonymous'
37
39
 
@@ -42,13 +44,13 @@ export function _tryCatch<T extends AnyFunction>(fn: T, opt: TryCatchOptions = {
42
44
  const r = await fn.apply(this, args)
43
45
 
44
46
  if (logSuccess) {
45
- console.log(`tryCatch.${fname} succeeded in ${_since(started)}`)
47
+ logger.log(`tryCatch.${fname} succeeded in ${_since(started)}`)
46
48
  }
47
49
 
48
50
  return r
49
51
  } catch (err) {
50
52
  if (logError) {
51
- console.warn(
53
+ logger.warn(
52
54
  `tryCatch.${fname} error in ${_since(started)}:\n${_stringifyAny(err, {
53
55
  includeErrorData: true,
54
56
  })}`,
@@ -1,4 +1,4 @@
1
- import { _since, _stringifyAny } from '..'
1
+ import { _since, _stringifyAny, CommonLogger } from '..'
2
2
 
3
3
  export interface PRetryOptions {
4
4
  /**
@@ -63,6 +63,11 @@ export interface PRetryOptions {
63
63
  * @default false
64
64
  */
65
65
  logNone?: boolean
66
+
67
+ /**
68
+ * Default to `console`
69
+ */
70
+ logger?: CommonLogger
66
71
  }
67
72
 
68
73
  /**
@@ -71,7 +76,13 @@ export interface PRetryOptions {
71
76
  */
72
77
  // eslint-disable-next-line @typescript-eslint/ban-types
73
78
  export function pRetry<T extends Function>(fn: T, opt: PRetryOptions = {}): T {
74
- const { maxAttempts = 4, delay: initialDelay = 1000, delayMultiplier = 2, predicate } = opt
79
+ const {
80
+ maxAttempts = 4,
81
+ delay: initialDelay = 1000,
82
+ delayMultiplier = 2,
83
+ predicate,
84
+ logger = console,
85
+ } = opt
75
86
 
76
87
  let { logFirstAttempt = false, logRetries = true, logFailures = false, logSuccess = false } = opt
77
88
 
@@ -95,18 +106,18 @@ export function pRetry<T extends Function>(fn: T, opt: PRetryOptions = {}): T {
95
106
  try {
96
107
  attempt++
97
108
  if ((attempt === 1 && logFirstAttempt) || (attempt > 1 && logRetries)) {
98
- console.log(`${fname} attempt #${attempt}...`)
109
+ logger.log(`${fname} attempt #${attempt}...`)
99
110
  }
100
111
 
101
112
  const r = await fn.apply(this, args)
102
113
 
103
114
  if (logSuccess) {
104
- console.log(`${fname} attempt #${attempt} succeeded in ${_since(started)}`)
115
+ logger.log(`${fname} attempt #${attempt} succeeded in ${_since(started)}`)
105
116
  }
106
117
  resolve(r)
107
118
  } catch (err) {
108
119
  if (logFailures) {
109
- console.warn(
120
+ logger.warn(
110
121
  `${fname} attempt #${attempt} error in ${_since(started)}:\n${_stringifyAny(err, {
111
122
  includeErrorData: true,
112
123
  })}`,