From dffb38cc8330cec53aa70f66cff1b105e9c027d1 Mon Sep 17 00:00:00 2001 From: Edgard Messias Date: Wed, 9 Dec 2020 17:10:54 -0300 Subject: [PATCH] feat: Improved logger using winston package --- docs/getting-started/configuring-logger.md | 91 ++++++++ package-lock.json | 235 +++++++++++++++------ package.json | 4 +- src/api/helpers/delete-file.ts | 22 +- src/api/layers/host.layer.ts | 132 +++++------- src/api/layers/listener.layer.ts | 4 +- src/config/create-config.ts | 16 +- src/controllers/initializer.ts | 46 ++-- src/controllers/welcome.ts | 25 +-- src/index.ts | 1 + src/types/spinnies.d.ts | 202 ------------------ src/utils/logger.ts | 49 +++++ src/utils/spinnies.ts | 64 ------ typedoc.json | 4 + 14 files changed, 426 insertions(+), 469 deletions(-) create mode 100644 docs/getting-started/configuring-logger.md delete mode 100644 src/types/spinnies.d.ts create mode 100644 src/utils/logger.ts delete mode 100644 src/utils/spinnies.ts diff --git a/docs/getting-started/configuring-logger.md b/docs/getting-started/configuring-logger.md new file mode 100644 index 000000000..d221cc90f --- /dev/null +++ b/docs/getting-started/configuring-logger.md @@ -0,0 +1,91 @@ +# Configuring the logger + +`Venom Bot` use [winston](https://github.com/winstonjs/winston) package for log management. + +`venom.defaultLogger` is a instance of `winston.createLogger`. + +## Default Log level + +The default log level is `info` + +```javascript +// Supports ES6 +// import * as venom from 'venom-bot'; +const venom = require('venom-bot'); + +// Levels: 'error', 'warn', 'info', 'http', 'verbose', 'debug', 'silly' +// All logs: 'silly' +venom.defaultLogger.level = 'silly'; + +// If you want stop console logging +venom.defaultLogger.transports.forEach((t) => (t.silent = true)); +``` + +## Using a custon logger + +```javascript +// Supports ES6 +// import * as venom from 'venom-bot'; +// import * as winston from 'winston'; +const venom = require('venom-bot'); +const winston = require('winston'); + +const logger = winston.createLogger({ + level: 'info', + format: winston.format.json(), + defaultMeta: { service: 'user-service' }, + transports: [ + // + // - Write all logs with level `error` and below to `error.log` + // - Write all logs with level `info` and below to `combined.log` + // + new winston.transports.File({ filename: 'error.log', level: 'error' }), + new winston.transports.File({ filename: 'combined.log' }), + ], +}); + +venom + .create( + 'sessionName', + undefined, + undefined, + { + logger: logger + } + ) + .then((client) => { + start(client); + }) + .catch((erro) => { + console.log(erro); + }); +``` + +## Log to file + +By default, venom-bot use the Console transport for logging. + +If you want to save the log to a file, you can configure +using the [winston transport](https://github.com/winstonjs/winston#transports) + +```javascript +// Supports ES6 +// import * as venom from 'venom-bot'; +// import * as winston from 'winston'; +const venom = require('venom-bot'); +const winston = require('winston'); + +// Optional: Remove all default transports +venom.defaultLogger.clear(); // Remove all transports + +// Create a file transport +const files = new winston.transports.File({ filename: 'combined.log' }); +venom.defaultLogger.add(files); // Add file transport + +// Optinal: create a custom console with error level +const console = new winston.transports.Console({ level: 'erro' }); +venom.defaultLogger.add(console); // Add console transport + +// Optinal: Remove the custom transport +venom.defaultLogger.remove(console); // Remove console transport +``` diff --git a/package-lock.json b/package-lock.json index 2683a60ec..8c154e494 100644 --- a/package-lock.json +++ b/package-lock.json @@ -438,6 +438,16 @@ "integrity": "sha512-VoNqai1vR5anRF5Tuh/+SWDFk7xi7oMwHrHrbm1BprYXjB2RJsWLhUrStMssDxEl5lW/z3EUdg8RvH/IUBccSQ==", "dev": true }, + "@dabh/diagnostics": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@dabh/diagnostics/-/diagnostics-2.0.2.tgz", + "integrity": "sha512-+A1YivoVDNNVCdfozHSR8v/jyuuLTMXwjWuxPFlFlUapXoGc+Gj9mDlTDDfrwl7rXCl2tNZ0kE8sIBO6YOn96Q==", + "requires": { + "colorspace": "1.1.x", + "enabled": "2.0.x", + "kuler": "^2.0.0" + } + }, "@eslint/eslintrc": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.2.2.tgz", @@ -1695,6 +1705,11 @@ "integrity": "sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg==", "dev": true }, + "async": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.0.tgz", + "integrity": "sha512-TR2mEZFVOj2pLStYxLht7TyfuRzaydfpxr3k9RpHIzMgw7A64dzsdqCxH1WJyQdoe8T10nDXd9wnEigmiuHIZw==" + }, "async-done": { "version": "1.3.2", "resolved": "https://registry.npmjs.org/async-done/-/async-done-1.3.2.tgz", @@ -2303,6 +2318,7 @@ "version": "3.1.0", "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", + "dev": true, "requires": { "restore-cursor": "^3.1.0" } @@ -2522,8 +2538,40 @@ "colors": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz", - "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==", - "dev": true + "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==" + }, + "colorspace": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/colorspace/-/colorspace-1.1.2.tgz", + "integrity": "sha512-vt+OoIP2d76xLhjwbBaucYlNSpPsrJWPlBTtwCpQKIu6/CSMutyzX93O/Do0qzpH3YoHEes8YEFXyZ797rEhzQ==", + "requires": { + "color": "3.0.x", + "text-hex": "1.0.x" + }, + "dependencies": { + "color": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/color/-/color-3.0.0.tgz", + "integrity": "sha512-jCpd5+s0s0t7p3pHQKpnJ0TpQKKdleP71LWcA0aqiljpiuAkOSUFN/dyH8ZwF0hRmFlrIuRhufds1QyEP9EB+w==", + "requires": { + "color-convert": "^1.9.1", + "color-string": "^1.5.2" + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" + } + } }, "combined-stream": { "version": "1.0.8", @@ -4320,6 +4368,11 @@ "integrity": "sha512-/kyM18EfinwXZbno9FyUGeFh87KC8HRQBQGildHZbEuRyWFOmv1U10o9BBp8XVZDVNNuQKyIGIu5ZYAAXJ0V2Q==", "dev": true }, + "enabled": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/enabled/-/enabled-2.0.0.tgz", + "integrity": "sha512-AKrN98kuwOzMIdAizXGI86UFBoo26CL21UM763y1h/GMSJ4/OHU9k2YlsmBpyScFo/wbLzWQJBMCW4+IO3/+OQ==" + }, "end-of-stream": { "version": "1.4.4", "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", @@ -4971,6 +5024,11 @@ "integrity": "sha1-5qdUzI8V5YmHqpy9J69m/W9OWvk=", "dev": true }, + "fast-safe-stringify": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.0.7.tgz", + "integrity": "sha512-Utm6CdzT+6xsDk2m8S6uL8VHxNwI6Jub+e9NYTcAms28T84pTa25GJQV9j0CY0N1rM8hK4x6grpF2BQf+2qwVA==" + }, "fastq": { "version": "1.9.0", "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.9.0.tgz", @@ -4988,6 +5046,11 @@ "pend": "~1.2.0" } }, + "fecha": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.0.tgz", + "integrity": "sha512-aN3pcx/DSmtyoovUudctc8+6Hl4T+hI9GBBHLjA76jdZl7+b1sgh5g4k+u/GL3dTy1/pnYzKp69FpJ0OicE3Wg==" + }, "figures": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz", @@ -5273,6 +5336,11 @@ } } }, + "fn.name": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fn.name/-/fn.name-1.1.0.tgz", + "integrity": "sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw==" + }, "follow-redirects": { "version": "1.13.0", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.13.0.tgz", @@ -6995,8 +7063,7 @@ "is-stream": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.0.tgz", - "integrity": "sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw==", - "dev": true + "integrity": "sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw==" }, "is-symbol": { "version": "1.0.3", @@ -7196,6 +7263,11 @@ "is-buffer": "^1.1.5" } }, + "kuler": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/kuler/-/kuler-2.0.0.tgz", + "integrity": "sha512-Xq9nH7KlWZmXAtodXDDRE7vs6DU1gTU8zYDHDiWLSip45Egwq3plLHzPn27NgvzL2r1LMPC1vdqh98sQxtqj4A==" + }, "last-run": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/last-run/-/last-run-1.1.1.tgz", @@ -7444,6 +7516,25 @@ "chalk": "^4.0.0" } }, + "logform": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/logform/-/logform-2.2.0.tgz", + "integrity": "sha512-N0qPlqfypFx7UHNn4B3lzS/b0uLqt2hmuoa+PpuXNYgozdJYAyauF5Ky0BWVjrxDlMWiT3qN4zPq3vVAfZy7Yg==", + "requires": { + "colors": "^1.2.1", + "fast-safe-stringify": "^2.0.4", + "fecha": "^4.2.0", + "ms": "^2.1.1", + "triple-beam": "^1.3.0" + }, + "dependencies": { + "ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + } + } + }, "longest": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/longest/-/longest-2.0.1.tgz", @@ -7906,7 +7997,8 @@ "mimic-fn": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", - "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==" + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "dev": true }, "mimic-response": { "version": "1.0.1", @@ -8517,10 +8609,19 @@ "wrappy": "1" } }, + "one-time": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/one-time/-/one-time-1.0.0.tgz", + "integrity": "sha512-5DXOiRKwuSEcQ/l0kGCF6Q3jcADFv5tSmRaJck/OqkVFcOzutB134KRSfF0xDrL39MNnqxbHBbUUcjZIhTgb2g==", + "requires": { + "fn.name": "1.x.x" + } + }, "onetime": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dev": true, "requires": { "mimic-fn": "^2.1.0" } @@ -10082,6 +10183,7 @@ "version": "3.1.0", "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", + "dev": true, "requires": { "onetime": "^5.1.0", "signal-exit": "^3.0.2" @@ -10641,62 +10743,6 @@ "integrity": "sha512-+orQK83kyMva3WyPf59k1+Y525csj5JejicWut55zeTWANuN17qSiSLUXWtzHeNWORSvT7GLDJ/E/XiIWoXBTw==", "dev": true }, - "spinnies": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/spinnies/-/spinnies-0.5.1.tgz", - "integrity": "sha512-WpjSXv9NQz0nU3yCT9TFEOfpFrXADY9C5fG6eAJqixLhvTX1jP3w92Y8IE5oafIe42nlF9otjhllnXN/QCaB3A==", - "requires": { - "chalk": "^2.4.2", - "cli-cursor": "^3.0.0", - "strip-ansi": "^5.2.0" - }, - "dependencies": { - "ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "requires": { - "color-convert": "^1.9.0" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "requires": { - "color-name": "1.1.3" - } - }, - "color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" - }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "requires": { - "has-flag": "^3.0.0" - } - } - } - }, "split": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/split/-/split-1.0.1.tgz", @@ -10742,8 +10788,7 @@ "stack-trace": { "version": "0.0.10", "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", - "integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=", - "dev": true + "integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=" }, "static-extend": { "version": "0.1.2", @@ -11117,6 +11162,11 @@ "integrity": "sha512-wiBrwC1EhBelW12Zy26JeOUkQ5mRu+5o8rpsJk5+2t+Y5vE7e842qtZDQ2g1NpX/29HdyFeJ4nSIhI47ENSxlQ==", "dev": true }, + "text-hex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/text-hex/-/text-hex-1.0.0.tgz", + "integrity": "sha512-uuVGNWzgJ4yhRaNSiubPY7OjISw4sw4E5Uv0wbjp+OzcbmVU/rsT8ujgcXJhn9ypzsgr5vlzpPqP+MBBKcGvbg==" + }, "text-table": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", @@ -11275,6 +11325,11 @@ "integrity": "sha1-n5up2e+odkw4dpi8v+sshI8RrbM=", "dev": true }, + "triple-beam": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/triple-beam/-/triple-beam-1.3.0.tgz", + "integrity": "sha512-XrHUvV5HpdLmIj4uVMxHggLbFSZYIn7HEWsqePZcI50pco+MPqJ50wMGY794X7AOOhxOBAjbkqfAbEe/QMp2Lw==" + }, "ts-loader": { "version": "8.0.11", "resolved": "https://registry.npmjs.org/ts-loader/-/ts-loader-8.0.11.tgz", @@ -12124,6 +12179,60 @@ "execa": "^4.0.2" } }, + "winston": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/winston/-/winston-3.3.3.tgz", + "integrity": "sha512-oEXTISQnC8VlSAKf1KYSSd7J6IWuRPQqDdo8eoRNaYKLvwSb5+79Z3Yi1lrl6KDpU6/VWaxpakDAtb1oQ4n9aw==", + "requires": { + "@dabh/diagnostics": "^2.0.2", + "async": "^3.1.0", + "is-stream": "^2.0.0", + "logform": "^2.2.0", + "one-time": "^1.0.0", + "readable-stream": "^3.4.0", + "stack-trace": "0.0.x", + "triple-beam": "^1.3.0", + "winston-transport": "^4.4.0" + } + }, + "winston-transport": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/winston-transport/-/winston-transport-4.4.0.tgz", + "integrity": "sha512-Lc7/p3GtqtqPBYYtS6KCN3c77/2QCev51DvcJKbkFPQNoj1sinkGwLGFDxkXY9J6p9+EPnYs+D90uwbnaiURTw==", + "requires": { + "readable-stream": "^2.3.7", + "triple-beam": "^1.2.0" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "requires": { + "safe-buffer": "~5.1.0" + } + } + } + }, "word-wrap": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz", diff --git a/package.json b/package.json index b2d9e4090..03926ba1a 100644 --- a/package.json +++ b/package.json @@ -110,8 +110,8 @@ "qrcode-terminal": "^0.12.0", "rxjs": "^6.6.3", "sharp": "^0.26.3", - "spinnies": "^0.5.1", - "tree-kill": "^1.2.2" + "tree-kill": "^1.2.2", + "winston": "^3.3.3" }, "optionalDependencies": { "fsevents": "^2.2.1" diff --git a/src/api/helpers/delete-file.ts b/src/api/helpers/delete-file.ts index dab83e29c..5b0e9b51b 100644 --- a/src/api/helpers/delete-file.ts +++ b/src/api/helpers/delete-file.ts @@ -54,32 +54,34 @@ MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM */ import path = require('path'); import { unlinkSync, existsSync } from 'fs'; -import * as Spinnies from 'spinnies'; +import { Logger } from 'winston'; export function deleteFiles( mergedOptions: any, - Session: String, - spinnies: Spinnies + session: string, + logger: Logger ) { - spinnies.add(`removeFile`, { text: '....' }); + logger.info('Removind token file...', { session, type: 'token' }); const pathTokens: string = path.join( path.resolve( process.cwd() + mergedOptions.mkdirFolderToken, mergedOptions.folderNameToken ), - `${Session}.data.json` + `${session}.data.json` ); if (existsSync(pathTokens)) { try { unlinkSync(pathTokens); - spinnies.succeed(`removeFile`, { - text: `Removed file: ${pathTokens}`, + logger.info(`Removed file: ${pathTokens}`, { + session, + type: 'token', }); } catch (err) { - spinnies.fail(`removeFile`, { - text: `Not removed file: ${pathTokens}`, + logger.warn(`Not removed file: ${pathTokens}`, { + session, + type: 'token', }); } } else { - spinnies.fail(`removeFile`, { text: `Not Files: ${pathTokens}` }); + logger.warn(`Not Files: ${pathTokens}`, { session, type: 'token' }); } } diff --git a/src/api/layers/host.layer.ts b/src/api/layers/host.layer.ts index f81dbdd4f..7c272c6ad 100644 --- a/src/api/layers/host.layer.ts +++ b/src/api/layers/host.layer.ts @@ -65,21 +65,13 @@ import { retrieveQR, } from '../../controllers/auth'; import { sleep } from '../../utils/sleep'; -import { getSpinnies } from '../../utils/spinnies'; -import * as Spinnies from 'spinnies'; +import { defaultLogger, LogLevel } from '../../utils/logger'; +import { Logger } from 'winston'; export class HostLayer { readonly session: string; readonly options: CreateConfig; - - protected spinnies: Spinnies = getSpinnies(); - protected spinStatus = { - apiInject: '', - autoCloseRemain: 0, - previousText: '', - previousStatus: null, - state: '', - }; + readonly logger: Logger; protected autoCloseInterval = null; @@ -87,78 +79,52 @@ export class HostLayer { this.session = session; this.options = { ...defaultOptions, ...options }; + this.logger = this.options.logger || defaultLogger; + this.page.on('load', () => { + this.log('verbose', 'Page loaded', { type: 'page' }); this.initialize(); }); this.page.on('close', () => { this.cancelAutoClose(); - this.spin('Page Closed', 'fail'); + this.log('error', 'Page Closed', { type: 'page' }); }); - this.spin('Initializing...', 'spinning'); + this.log('info', 'Initializing...'); this.initialize(); } - protected spin(text?: string, status?: Spinnies.SpinnerStatus) { - const name = `session-${this.session}`; - - text = text || this.spinStatus.previousText; - this.spinStatus.previousText = text; - - status = - status || (this.spinStatus.previousStatus as Spinnies.SpinnerStatus); - this.spinStatus.previousStatus = status; - - let fullText = `{session: ${this.session}`; - if (this.spinStatus.apiInject) { - fullText += `, apiInject: ${this.spinStatus.apiInject}`; - } - if (this.spinStatus.state) { - fullText += `, state: ${this.spinStatus.state}`; - } - if (this.autoCloseInterval) { - if (!this.options.disableSpins && this.spinStatus.autoCloseRemain > 0) { - fullText += `, autoCloneRemain: ${this.spinStatus.autoCloseRemain}`; - } else if (this.options.autoClose > 0) { - fullText += `, autoClose: ${Math.round(this.options.autoClose / 1000)}`; - } - } - fullText += `}: ${text}`; - - let prevText = ''; - - try { - prevText = this.spinnies.pick(name).text; - } catch (error) { - this.spinnies.add(name, { text: fullText, status }); - prevText = fullText; - } - if (prevText !== fullText) { - this.spinnies.update(name, { - text: fullText, - status, - }); - } + protected log(level: LogLevel, message: string, meta: object = {}) { + this.logger.log({ + level, + message, + session: this.session, + type: 'client', + ...meta, + }); } protected async initialize() { - this.spinStatus.apiInject = 'injecting'; - this.spin(); + this.log('verbose', 'Injecting wapi.js'); await injectApi(this.page) .then(() => { - this.spinStatus.apiInject = 'injected'; + this.log('verbose', 'wapi.js injected'); }) .catch(() => { - this.spinStatus.apiInject = 'failed'; + this.log('verbose', 'wapi.js failed'); }); - this.spin(); } protected tryAutoClose() { + if (this.autoCloseInterval) { + this.cancelAutoClose(); + } + if ( this.options.autoClose > 0 && !this.autoCloseInterval && !this.page.isClosed() ) { + this.log('info', 'Closing the page'); try { this.page.close(); } catch (error) {} @@ -167,17 +133,20 @@ export class HostLayer { protected startAutoClose() { if (this.options.autoClose > 0 && !this.autoCloseInterval) { - let remain = this.options.autoClose; + const seconds = Math.round(this.options.autoClose / 1000); + this.log('info', `Auto close configured to ${seconds}s`); + + let remain = seconds; this.autoCloseInterval = setInterval(() => { if (this.page.isClosed()) { this.cancelAutoClose(); return; } - remain -= 1000; - this.spinStatus.autoCloseRemain = Math.round(remain / 1000); - this.spin(); + remain -= 1; + if (remain % 10 === 0 || remain <= 5) { + this.log('http', `Auto close remain: ${remain}s`); + } if (remain <= 0) { - this.cancelAutoClose(); this.tryAutoClose(); } }, 1000); @@ -187,7 +156,6 @@ export class HostLayer { protected cancelAutoClose() { clearInterval(this.autoCloseInterval); this.autoCloseInterval = null; - this.spin(); } public async getQrCode() { @@ -228,9 +196,13 @@ export class HostLayer { } if (this.options.logQR) { - this.spin(`Waiting for QRCode Scan (Attempt ${attempt})...:\n${qr}`); + this.log( + 'info', + `Waiting for QRCode Scan (Attempt ${attempt})...:\n${qr}`, + { code: urlCode } + ); } else { - this.spin(`Waiting for QRCode Scan: Attempt ${attempt}`); + this.log('verbose', `Waiting for QRCode Scan: Attempt ${attempt}`); } if (catchQR) { @@ -260,7 +232,7 @@ export class HostLayer { ) => void, statusFind?: (statusGet: string, session: string) => void ) { - this.spin('Waiting page load', 'spinning'); + this.log('info', 'Waiting page load'); await this.page .waitForFunction(`document.readyState === 'complete'`) @@ -268,63 +240,59 @@ export class HostLayer { this.startAutoClose(); - this.spin('Checking is logged...'); + this.log('http', 'Checking is logged...'); let authenticated = await isAuthenticated(this.page).catch(() => null); if (authenticated === false) { - this.spin('Waiting for QRCode Scan...'); + this.log('http', 'Waiting for QRCode Scan...'); statusFind && statusFind('notLogged', this.session); await this.waitForQrCodeScan(catchQR); - this.spin('Checking QRCode status...'); + this.log('http', 'Checking QRCode status...'); // Wait for interface update await sleep(200); authenticated = await isAuthenticated(this.page).catch(() => null); if (authenticated) { - this.spin('QRCode Success'); + this.log('http', 'QRCode Success'); statusFind && statusFind('qrReadSuccess', this.session); } else { - this.spin('QRCode Fail', 'fail'); + this.log('warn', 'QRCode Fail'); statusFind && statusFind('qrReadFail', this.session); - this.cancelAutoClose(); this.tryAutoClose(); throw 'Failed to read the QRCode'; } } else if (authenticated === true) { - this.spin('Authenticated'); + this.log('http', 'Authenticated'); statusFind && statusFind('isLogged', this.session); } if (authenticated === true) { // Wait for interface update await sleep(200); - this.spin('Checking phone is connected...'); + this.log('info', 'Checking phone is connected...'); const inChat = await this.waitForInChat(); if (!inChat) { - this.spin('Phone not connected', 'fail'); + this.log('warn', 'Phone not connected'); statusFind && statusFind('phoneNotConnected', this.session); - this.cancelAutoClose(); this.tryAutoClose(); throw 'Phone not connected'; } this.cancelAutoClose(); - this.spin('Connected', 'succeed'); + this.log('http', 'Connected'); statusFind && statusFind('inChat', this.session); return true; } if (authenticated === false) { - this.cancelAutoClose(); this.tryAutoClose(); - this.spin('Not logged', 'fail'); + this.log('warn', 'Not logged'); throw 'Not logged'; } - this.cancelAutoClose(); this.tryAutoClose(); - this.spin('Unknow error', 'fail'); + this.log('error', 'Unknow error'); throw 'Unknow error'; } diff --git a/src/api/layers/listener.layer.ts b/src/api/layers/listener.layer.ts index 356e33d44..7867ca33a 100644 --- a/src/api/layers/listener.layer.ts +++ b/src/api/layers/listener.layer.ts @@ -79,8 +79,7 @@ export class ListenerLayer extends ProfileLayer { super(page, session, options); this.listenerEmitter.on(ExposedFn.onInterfaceChange, (state) => { - this.spinStatus.state = `${state.mode} (${state.displayInfo})`; - this.spin(); + this.log('http', `Current state: ${state.mode} (${state.displayInfo})`); }); } @@ -99,6 +98,7 @@ export class ListenerLayer extends ProfileLayer { .catch(() => false); if (!has) { + this.log('debug', `Exposing ${func} function`); await this.page .exposeFunction(func, (...args) => this.listenerEmitter.emit(func, ...args) diff --git a/src/config/create-config.ts b/src/config/create-config.ts index b45785af3..6351eb959 100644 --- a/src/config/create-config.ts +++ b/src/config/create-config.ts @@ -52,6 +52,10 @@ MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNMMNMNMMMNMMNNMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNMMNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM */ + +import { Logger } from 'winston'; +import { defaultLogger } from '../utils/logger'; + // Server config export interface CreateConfig { /** folder name when saving tokens @@ -99,11 +103,6 @@ export interface CreateConfig { * @default true */ logQR?: boolean; - /** - * Will disable Spinnies animation, useful for containers (docker) for a better log - * @default false - */ - disableSpins?: boolean; /** * Will disable the welcoming message which appears in the beginning * @default false @@ -129,6 +128,11 @@ export interface CreateConfig { * @default false */ waitForLogin?: boolean; + /** + * Wait for in chat to return a instance of {@link Whatsapp} + * @default false + */ + logger?: Logger; } export const defaultOptions: CreateConfig = { folderNameToken: 'tokens', @@ -141,10 +145,10 @@ export const defaultOptions: CreateConfig = { browserWS: '', browserArgs: [''], puppeteerOptions: {}, - disableSpins: false, disableWelcome: false, updatesLog: true, autoClose: 60000, createPathFileToken: true, waitForLogin: true, + logger: defaultLogger, }; diff --git a/src/controllers/initializer.ts b/src/controllers/initializer.ts index 3fe8570e3..36e6b1c15 100644 --- a/src/controllers/initializer.ts +++ b/src/controllers/initializer.ts @@ -58,7 +58,6 @@ import { CreateConfig, defaultOptions } from '../config/create-config'; import { SessionTokenCkeck, saveToken } from './auth'; import { initWhatsapp, initBrowser } from './browser'; import { checkUpdates, welcomeScreen } from './welcome'; -import { getSpinnies } from '../utils/spinnies'; import { SocketState } from '../api/model/enum'; import { deleteFiles } from '../api/helpers'; import { tokenSession } from '../config/tokenSession.config'; @@ -136,53 +135,53 @@ export async function create( let browserToken: any; - const spinnies = getSpinnies({ - disableSpins: options ? options.disableSpins : false, - }); - const mergedOptions = { ...defaultOptions, ...options }; + const logger = mergedOptions.logger; + if (!mergedOptions.disableWelcome) { welcomeScreen(); } if (mergedOptions.updatesLog) { - await checkUpdates(spinnies); + await checkUpdates(); } // Initialize whatsapp - spinnies.add(`browser-${session}`, { - text: 'Initializing browser...', - }); - + logger.info('Initializing browser...', { session, type: 'browser' }); const browser = await initBrowser(session, mergedOptions); if (browser === 'connect') { - spinnies.fail(`browser-${session}`, { - text: `Error when try to connect ${mergedOptions.browserWS}`, + logger.error(`Error when try to connect ${mergedOptions.browserWS}`, { + session, + type: 'browser', }); throw `Error when try to connect ${mergedOptions.browserWS}`; } if (browser === 'launch') { - spinnies.fail(`browser-${session}`, { - text: `Error no open browser`, + logger.error(`Error no open browser`, { + session, + type: 'browser', }); throw `Error no open browser`; } if (typeof browser === 'object') { - spinnies.update(`browser-${session}`, { - text: 'checking headless...', + logger.http('checking headless...', { + session, + type: 'browser', }); if (mergedOptions.headless) { - spinnies.succeed(`browser-${session}`, { - text: 'headless option is active, browser hidden', + logger.http('headless option is active, browser hidden', { + session, + type: 'browser', }); } else { - spinnies.succeed(`browser-${session}`, { - text: 'headless option is disabled, browser visible', + logger.http('headless option is disabled, browser visible', { + session, + type: 'browser', }); } @@ -229,7 +228,7 @@ export async function create( if (state === SocketState.CONNECTED) { setTimeout(() => { saveToken(waPage, session, mergedOptions).catch((e) => { - console.log(e); + logger.error(e, { session }); }); }, 1000); } @@ -246,10 +245,11 @@ export async function create( state === SocketState.UNPAIRED || state === SocketState.UNPAIRED_IDLE ) { + logger.info('Session Unpaired', { session }); if (statusFind) { statusFind('desconnectedMobile', session); } - deleteFiles(mergedOptions, session, spinnies); + deleteFiles(mergedOptions, session, logger); client.waitForLogin(catchQR, statusFind).catch(() => {}); } }); @@ -259,7 +259,7 @@ export async function create( const debugURL = `http://localhost:${readFileSync( `./${session}/DevToolsActivePort` ).slice(0, -54)}`; - console.log(`\nDebug: \x1b[34m${debugURL}\x1b[0m`); + logger.info(`\nDebug: \x1b[34m${debugURL}\x1b[0m`); } return client; diff --git a/src/controllers/welcome.ts b/src/controllers/welcome.ts index bfc2c19fb..aa71609d4 100644 --- a/src/controllers/welcome.ts +++ b/src/controllers/welcome.ts @@ -1,7 +1,7 @@ import * as boxen from 'boxen'; import * as chalk from 'chalk'; import latestVersion from 'latest-version'; -import * as Spinnies from 'spinnies'; +import { defaultLogger as logger } from '../utils/logger'; import { upToDate } from '../utils/semver'; const { version } = require('../../package.json'); @@ -14,7 +14,7 @@ export function welcomeScreen() { return; } welcomeShown = true; - console.log(` + logger.info(` ▐█ ██ █░▐█▀▀▀░▐█ ▄█▀▀█▄ ▄█▀▀█▄ ▐██ ██▌ ▓█▀▀▀░ █▌▐██▄▓█ ▐█▄▄▄ ▐█ ▐█ █▒ ▐█▄▐█▀▌ ▐▌█▌ ▓█▄▄▄ @@ -32,29 +32,24 @@ export function welcomeScreen() { ▀░ \n`); } -export async function checkUpdates(spinnies: Spinnies) { +export async function checkUpdates() { // Check for updates if needed if (!updatesChecked) { updatesChecked = true; - spinnies.add('venom-version-spinner', { - text: 'Checking for updates', - }); - await checkVenomVersion(spinnies); + await checkVenomVersion(); } } /** * Checs for a new versoin of venom and logs */ -async function checkVenomVersion(spinnies: Spinnies) { - spinnies.update('venom-version-spinner', { text: 'Checking for updates...' }); +async function checkVenomVersion() { + logger.info('Checking for updates'); await latestVersion('venom-bot').then((latest) => { if (upToDate(version, latest)) { - spinnies.succeed('venom-version-spinner', { text: "You're up to date" }); + logger.info("You're up to date"); } else { - spinnies.succeed('venom-version-spinner', { - text: 'There is a new version available', - }); + logger.info('There is a new version available'); logUpdateAvailable(version, latest); } }); @@ -72,8 +67,8 @@ function logUpdateAvailable(current: string, latest: string) { `Update your package by running:\n\n` + `${chalk.bold('\>')} ${chalk.blueBright('npm update venom-bot')}`; - console.log(boxen(newVersionLog, { padding: 1 })); - console.log( + logger.info(boxen(newVersionLog, { padding: 1 })); + logger.info( `For more info visit: ${chalk.underline( 'https://github.com/orkestral/venom/blob/master/Update.md' )}\n` diff --git a/src/index.ts b/src/index.ts index 9ef3105e8..4faf77d3c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -73,3 +73,4 @@ export { CreateOptions, StatusFind, } from './controllers/initializer'; +export { defaultLogger } from './utils/logger'; diff --git a/src/types/spinnies.d.ts b/src/types/spinnies.d.ts deleted file mode 100644 index ceed317e7..000000000 --- a/src/types/spinnies.d.ts +++ /dev/null @@ -1,202 +0,0 @@ -/* -NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN -MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM -mMMMMMMMMMNNNmmNNNMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM -mmNMMNMMMMNNNNNmmmddhdddNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM -mddNMMNy:/odNmmddmmNNmdhhddmNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM -NmmdNMNd:--+dNmmddhhddmmhsyhhmdmmNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM -NmNmdNmy:.-oyNmmmhmdhho+sososyhhhddNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM -NmmNdh+-`.:oyNNdmmdmmdo-://oysssyhhhdmNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM -Nmmmoyyyo+osdNmdmmddNNhs+/::/+osyssydyhdNMMMMMMMMMMMM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MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM -*/ -declare module 'spinnies' { - namespace Spinnies { - type StopAllStatus = 'succeed' | 'fail' | 'stopped'; - type SpinnerStatus = StopAllStatus | 'spinning' | 'non-spinnable'; - - interface Spinner { - interval: number; - frames: string[]; - } - - interface SpinnerOptions { - /** - * Optional text to show in the spinner. If none is provided, the name field will be shown. - */ - text?: string; - - /** - * Optional, indent the spinner with the given number of spaces. - * */ - indent?: number; - - /** - * Initial status of the spinner. Valid statuses are: succeed, fail, spinning, non-spinnable and stopped. - */ - status?: SpinnerStatus; - - /** - * Any valid chalk color. - */ - color?: string; - - /** - * Any valid chalk color. - */ - succeedColor?: string; - - /** - * Any valid chalk color. - */ - failColor?: string; - } - - interface Options { - /** - * Any valid chalk color. The default value is white. - */ - color?: string; - - /** - * Any valid chalk color. The default value is green. - */ - succeedColor?: string; - - /** - * Any valid chalk color. The default value is red. - */ - failColor?: string; - - /** - * Any valid chalk color. The default value is greenBright. - */ - spinnerColor?: string; - - /** - * The default value is ✓. - */ - succeedPrefix?: string; - - /** - * The default value is ✖. - */ - failPrefix?: string; - - /** - * Disable spins (will still print raw messages). - */ - disableSpins?: boolean; - - /** - * Spinner configuration - */ - spinner?: Spinner; - } - } - - class Spinnies { - static dots: Spinnies.Spinner; - static dashes: Spinnies.Spinner; - - constructor(options?: Spinnies.Options); - - /** - * Add a new spinner with the given name. - */ - add: ( - name: string, - options?: Spinnies.SpinnerOptions - ) => Spinnies.SpinnerOptions; - - /** - * Get spinner by name. - */ - pick: (name: string) => Spinnies.SpinnerOptions; - - /** - * Remove spinner with name. - */ - remove: (name: string) => Spinnies.SpinnerOptions; - - /** - * Updates the spinner with name name with the provided options. - */ - update: ( - name: string, - options?: Spinnies.SpinnerOptions - ) => Spinnies.SpinnerOptions; - - /** - * Sets the specified spinner status as succeed. - */ - succeed: ( - name: string, - options?: Spinnies.SpinnerOptions - ) => Spinnies.SpinnerOptions; - - /** - * Sets the specified spinner status as fail. - */ - fail: ( - name: string, - options?: Spinnies.SpinnerOptions - ) => Spinnies.SpinnerOptions; - - /** - * Stops the spinners and sets the non-succeeded and non-failed ones to the provided status. - */ - stopAll: ( - status?: Spinnies.StopAllStatus - ) => { [name: string]: Spinnies.SpinnerOptions }; - - /** - * @returns false if all spinners have succeeded, failed or have been stopped - */ - hasActiveSpinners: () => boolean; - } - - export = Spinnies; -} diff --git a/src/utils/logger.ts b/src/utils/logger.ts new file mode 100644 index 000000000..609217201 --- /dev/null +++ b/src/utils/logger.ts @@ -0,0 +1,49 @@ +import { config, createLogger, format, transports } from 'winston'; +import { TransformableInfo } from 'logform'; + +export type LogLevel = + | 'error' + | 'warn' + | 'info' + | 'http' + | 'verbose' + | 'debug' + | 'silly'; + +export interface MetaInfo { + session?: string; + type?: string; +} + +export interface SessionInfo extends TransformableInfo, MetaInfo {} + +export const formatLabelSession = format((info: SessionInfo, opts?: any) => { + const parts = []; + if (info.session) { + parts.push(info.session); + delete info.session; + } + if (info.type) { + parts.push(info.type); + delete info.type; + } + + if (parts.length) { + let prefix = parts.join(':'); + info.message = `[${prefix}] ${info.message}`; + } + return info; +}); + +export const defaultLogger = createLogger({ + level: 'info', + levels: config.npm.levels, + format: format.combine( + formatLabelSession(), + format.colorize(), + format.padLevels(), + format.simple() + ), + // defaultMeta: { service: 'venon-bot' }, + transports: [new transports.Console()], +}); diff --git a/src/utils/spinnies.ts b/src/utils/spinnies.ts deleted file mode 100644 index 4a8a21c5c..000000000 --- a/src/utils/spinnies.ts +++ /dev/null @@ -1,64 +0,0 @@ -/* -NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN -MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM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MMN/ yMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM -MMMMMMN/ +NMMMN- /yyyyyys d. dMMMMNo` dNy-+ymmmho-+NN- dMMMMMMMMN/ yMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM -MMMMMMMNyNMMMMN+::::::::::m+/mMMMMMMd: dMMNho///+ymMMN+/mMMMMMMMMNs/hMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM -MMMMMMMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMNsmMMMMMMMMMMMMMMNNNNMMNNNMMNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM -MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNMMMMMMMMMMMMMMNMMNMNMMMNMMNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM -MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNMMNMNMMMNMMNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM -MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNMMNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM -MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM -*/ -import * as Spinnies from 'spinnies'; - -let spinnies: Spinnies = null; - -export function getSpinnies(options?: Spinnies.Options): Spinnies { - if (!spinnies) { - spinnies = new Spinnies(options); - } - return spinnies; -} diff --git a/typedoc.json b/typedoc.json index 82aa9c03f..7701dad4d 100644 --- a/typedoc.json +++ b/typedoc.json @@ -21,6 +21,10 @@ "title": "Creating a Client", "source": "./docs/getting-started/creating-client.md" }, + { + "title": "Configuring the logger", + "source": "./docs/getting-started/configuring-logger.md" + }, { "title": "Basic Functions", "source": "./docs/getting-started/basic-functions.md"