1 |
|
2 |
|
3 | const color = require('colorette');
|
4 | const { inspect } = require('util');
|
5 | const { isFunction, isNil, isString } = require('lodash');
|
6 |
|
7 | class Logger {
|
8 | constructor(config) {
|
9 | const {
|
10 | log: {
|
11 | debug,
|
12 | warn,
|
13 | error,
|
14 | deprecate,
|
15 | inspectionDepth,
|
16 | enableColors,
|
17 | } = {},
|
18 | } = config;
|
19 | this._inspectionDepth = inspectionDepth || 5;
|
20 | this._enableColors = resolveIsEnabledColors(enableColors);
|
21 | this._debug = debug;
|
22 | this._warn = warn;
|
23 | this._error = error;
|
24 | this._deprecate = deprecate;
|
25 | }
|
26 |
|
27 | _log(message, userFn, colorFn) {
|
28 | if (!isNil(userFn) && !isFunction(userFn)) {
|
29 | throw new TypeError('Extensions to knex logger must be functions!');
|
30 | }
|
31 |
|
32 | if (isFunction(userFn)) {
|
33 | userFn(message);
|
34 | return;
|
35 | }
|
36 |
|
37 | if (!isString(message)) {
|
38 | message = inspect(message, {
|
39 | depth: this._inspectionDepth,
|
40 | colors: this._enableColors,
|
41 | });
|
42 | }
|
43 |
|
44 | console.log(colorFn ? colorFn(message) : message);
|
45 | }
|
46 |
|
47 | debug(message) {
|
48 | this._log(message, this._debug);
|
49 | }
|
50 |
|
51 | warn(message) {
|
52 | this._log(message, this._warn, color.yellow);
|
53 | }
|
54 |
|
55 | error(message) {
|
56 | this._log(message, this._error, color.red);
|
57 | }
|
58 |
|
59 | deprecate(method, alternative) {
|
60 | const message = `${method} is deprecated, please use ${alternative}`;
|
61 |
|
62 | this._log(message, this._deprecate, color.yellow);
|
63 | }
|
64 | }
|
65 |
|
66 | function resolveIsEnabledColors(enableColorsParam) {
|
67 | if (!isNil(enableColorsParam)) {
|
68 | return enableColorsParam;
|
69 | }
|
70 |
|
71 | if (process && process.stdout) {
|
72 | return process.stdout.isTTY;
|
73 | }
|
74 |
|
75 | return false;
|
76 | }
|
77 |
|
78 | module.exports = Logger;
|