@vvlad1973/simple-logger 1.2.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.
@@ -0,0 +1,21 @@
1
+ {
2
+ // Используйте IntelliSense, чтобы узнать о возможных атрибутах.
3
+ // Наведите указатель мыши, чтобы просмотреть описания существующих атрибутов.
4
+ // Для получения дополнительной информации посетите: https://go.microsoft.com/fwlink/?linkid=830387
5
+ "version": "0.2.0",
6
+ "configurations": [
7
+ {
8
+ "type": "node",
9
+ "request": "launch",
10
+ "name": "Запустить программу",
11
+ "skipFiles": [
12
+ "<node_internals>/**"
13
+ ],
14
+ "program": "${workspaceFolder}\\src\\__test__\\simple-logger.test.ts",
15
+ "preLaunchTask": "tsc: build - tsconfig.json",
16
+ "outFiles": [
17
+ "${workspaceFolder}/dist/**/*.js"
18
+ ]
19
+ }
20
+ ]
21
+ }
package/LICENSE ADDED
@@ -0,0 +1,19 @@
1
+ # MIT License with Commercial Use
2
+
3
+ Copyright (c) 2022 Vladislav Vnukovskiy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software.
6
+
7
+ Commercial Use:
8
+
9
+ The user is allowed to use the Software for commercial purposes, subject to the following conditions:
10
+
11
+ The user must agree to share a portion of their revenue with the author of the Software.
12
+
13
+ The author of the Software reserves the right to verify the accuracy and size of the revenue earned by the user through the use of the Software. This provision is a mandatory condition for the commercial use of the Software.
14
+
15
+ If the user does not agree to these conditions, they may not use the Software for commercial purposes.
16
+
17
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,97 @@
1
+ # @vvlad1973/simple-logger
2
+
3
+ A simple logger module for Node.js applications with support for various logging levels.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install vvlad1973-simple-logger
9
+ ```
10
+
11
+ ## Features
12
+
13
+ - Supports logging at different levels: TRACE, DEBUG, INFO, WARN, ERROR, FATAL.
14
+ - Allows integration with external logging libraries like Pino.
15
+
16
+ ## Usage
17
+
18
+ ### Simple Logger
19
+
20
+ ```javascript
21
+
22
+ import SimpleLogger from 'vvlad1973-simple-logger';
23
+
24
+ const logger = new SimpleLogger('DEBUG');
25
+
26
+ logger.debug('Debug message');
27
+ logger.info('Info message');
28
+ logger.warn('Warning message');
29
+ logger.error('Error message');
30
+ logger.fatal('Fatal error message');
31
+ ```
32
+
33
+ ### Integration with Pino
34
+
35
+ ```javascript
36
+ import pino from 'pino';
37
+ import SimpleLogger from 'vvlad1973-simple-logger';
38
+
39
+ // Initialize Pino logger
40
+ const pinoLogger = pino({
41
+ prettyPrint: true,
42
+ });
43
+
44
+ // Use Pino logger with SimpleLogger
45
+ const logger = new SimpleLogger('DEBUG', pinoLogger);
46
+
47
+ logger.debug('Debug message');
48
+ logger.info('Info message');
49
+ logger.warn('Warning message');
50
+ logger.error('Error message');
51
+ logger.fatal('Fatal error message');
52
+ ```
53
+
54
+ ## API
55
+
56
+ ### new SimpleLogger(level, externalLogger)
57
+
58
+ Creates a new instance of SimpleLogger.
59
+
60
+ - level (optional): Initial logging level. Defaults to 'INFO'.
61
+ - externalLogger (optional): External logger instance. Can be an object with methods (trace, debug, info, warn, error, fatal) or any other logger compatible with these methods.
62
+
63
+ ### setLevel(level)
64
+
65
+ Sets the logging level of the logger instance.
66
+
67
+ - level: The logging level to set ('TRACE', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL').
68
+
69
+ ### setExternalLogger(logger)
70
+
71
+ Sets an external logger instance to be used by SimpleLogger.
72
+
73
+ - logger: External logger instance. Should be an object with methods (trace, debug, info, warn, error, fatal) or any other logger compatible with these methods.
74
+
75
+ ### logFunctionStart(functionName?)
76
+
77
+ Logs the start of a function.
78
+
79
+ - functionName (optional): Name of the function to log. If not provided, attempts to retrieve the caller function name.
80
+
81
+ ### logFunctionEnd(functionName?)
82
+
83
+ Logs the end of a function.
84
+
85
+ - functionName (optional): Name of the function to log. If not provided, attempts to retrieve the caller function name.
86
+
87
+ ### Documentation
88
+
89
+ Full information about the package is available in the [./docs](./docs/index.html) directory
90
+
91
+ ### License
92
+
93
+ This project is licensed under the MIT License with Commercial Use.
94
+
95
+ ## Author
96
+
97
+ Vladislav Vnukovskiy <vvlad1973@gmail.com>
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,113 @@
1
+ import { describe, it, beforeEach } from 'node:test';
2
+ import assert from 'assert';
3
+ import SimpleLogger from '../simple-logger.js';
4
+ function createMockLoggerMethod() {
5
+ const calls = [];
6
+ const mockFn = function (...args) {
7
+ calls.push(args);
8
+ };
9
+ mockFn.mock = { calls };
10
+ return mockFn;
11
+ }
12
+ function createNoopMethod() {
13
+ const calls = [];
14
+ const mockFn = function (...args) { };
15
+ mockFn.mock = { calls };
16
+ return mockFn;
17
+ }
18
+ function createExternalLoggerMock() {
19
+ return {
20
+ trace: createMockLoggerMethod(),
21
+ debug: createMockLoggerMethod(),
22
+ info: createMockLoggerMethod(),
23
+ warn: createMockLoggerMethod(),
24
+ error: createMockLoggerMethod(),
25
+ fatal: createMockLoggerMethod(),
26
+ silent: createMockLoggerMethod(),
27
+ };
28
+ }
29
+ describe('SimpleLogger', () => {
30
+ let logger;
31
+ let externalLoggerMock;
32
+ beforeEach(() => {
33
+ externalLoggerMock = createExternalLoggerMock();
34
+ logger = new SimpleLogger('info', externalLoggerMock);
35
+ });
36
+ it('should call external logger methods appropriately', () => {
37
+ logger.trace('trace message');
38
+ logger.debug('debug message');
39
+ logger.info('info message');
40
+ logger.warn('warn message');
41
+ logger.error('error message');
42
+ logger.fatal('fatal message');
43
+ assert.strictEqual(externalLoggerMock.trace.mock.calls.length, 0);
44
+ assert.strictEqual(externalLoggerMock.debug.mock.calls.length, 0);
45
+ assert.strictEqual(externalLoggerMock.info.mock.calls.length, 1);
46
+ assert.strictEqual(externalLoggerMock.info.mock.calls[0][0], 'info message');
47
+ assert.strictEqual(externalLoggerMock.warn.mock.calls.length, 1);
48
+ assert.strictEqual(externalLoggerMock.warn.mock.calls[0][0], 'warn message');
49
+ assert.strictEqual(externalLoggerMock.error.mock.calls.length, 1);
50
+ assert.strictEqual(externalLoggerMock.error.mock.calls[0][0], 'error message');
51
+ assert.strictEqual(externalLoggerMock.fatal.mock.calls.length, 1);
52
+ assert.strictEqual(externalLoggerMock.fatal.mock.calls[0][0], 'fatal message');
53
+ });
54
+ it('should log function start and end', () => {
55
+ logger.setLevel('TRACE');
56
+ function testFunction() {
57
+ logger.logFunctionStart();
58
+ logger.logFunctionEnd();
59
+ }
60
+ testFunction();
61
+ assert.strictEqual(externalLoggerMock.trace.mock.calls.length, 2);
62
+ assert.strictEqual(externalLoggerMock.trace.mock.calls[0][0], 'Function start: testFunction');
63
+ assert.strictEqual(externalLoggerMock.trace.mock.calls[1][0], 'Function end: testFunction');
64
+ });
65
+ });
66
+ describe('SimpleLogger2', () => {
67
+ let logger;
68
+ let externalLoggerMock;
69
+ beforeEach(() => {
70
+ externalLoggerMock = createExternalLoggerMock();
71
+ logger = new SimpleLogger('info', externalLoggerMock);
72
+ });
73
+ it('should use console as default external logger', () => {
74
+ const defaultLogger = new SimpleLogger();
75
+ assert.ok(defaultLogger);
76
+ });
77
+ it('should set the correct log level', () => {
78
+ logger.setLevel('DEBUG');
79
+ assert.notStrictEqual(logger.trace, () => { });
80
+ assert.strictEqual(typeof logger.debug, 'function');
81
+ assert.strictEqual(typeof logger.info, 'function');
82
+ });
83
+ it('should call external logger methods appropriately', () => {
84
+ logger.trace('trace message');
85
+ logger.debug('debug message');
86
+ logger.info('info message');
87
+ logger.warn('warn message');
88
+ logger.error('error message');
89
+ logger.fatal('fatal message');
90
+ assert.strictEqual(externalLoggerMock.trace.mock.calls.length, 0); // because default level is INFO
91
+ assert.strictEqual(externalLoggerMock.debug.mock.calls.length, 0); // because default level is INFO
92
+ assert.strictEqual(externalLoggerMock.info.mock.calls.length, 1);
93
+ assert.strictEqual(externalLoggerMock.info.mock.calls[0][0], 'info message');
94
+ assert.strictEqual(externalLoggerMock.warn.mock.calls.length, 1);
95
+ assert.strictEqual(externalLoggerMock.warn.mock.calls[0][0], 'warn message');
96
+ assert.strictEqual(externalLoggerMock.error.mock.calls.length, 1);
97
+ assert.strictEqual(externalLoggerMock.error.mock.calls[0][0], 'error message');
98
+ assert.strictEqual(externalLoggerMock.fatal.mock.calls.length, 1);
99
+ assert.strictEqual(externalLoggerMock.fatal.mock.calls[0][0], 'fatal message');
100
+ });
101
+ it('should log function start and end', () => {
102
+ logger.setLevel('TRACE');
103
+ function testFunction() {
104
+ logger.logFunctionStart();
105
+ logger.logFunctionEnd();
106
+ }
107
+ testFunction();
108
+ assert.strictEqual(externalLoggerMock.trace.mock.calls.length, 2);
109
+ assert.strictEqual(externalLoggerMock.trace.mock.calls[0][0], 'Function start: testFunction');
110
+ assert.strictEqual(externalLoggerMock.trace.mock.calls[1][0], 'Function end: testFunction');
111
+ });
112
+ });
113
+ //# sourceMappingURL=simple-logger.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"simple-logger.test.js","sourceRoot":"","sources":["../../src/__test__/simple-logger.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACrD,OA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/B,CAAC;QACF,MAAM,CAAC,WAAW,CAChB,kBAAkB,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EACzC,4BAA4B,CAC7B,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -0,0 +1,2 @@
1
+ export { default } from './simple-logger.js';
2
+ export * from './simple-logger.js';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { default } from './simple-logger.js';
2
+ export * from './simple-logger.js';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAA;AAC5C,cAAc,oBAAoB,CAAA"}
@@ -0,0 +1,80 @@
1
+ /**
2
+ * A module for simple logging with various logging levels.
3
+ * @module SimpleLogger
4
+ */
5
+ export type ExternalLogger = {
6
+ trace?: LogFn;
7
+ debug?: LogFn;
8
+ info?: LogFn;
9
+ warn?: LogFn;
10
+ error?: LogFn;
11
+ fatal?: LogFn;
12
+ silent?: LogFn;
13
+ level?: string;
14
+ };
15
+ interface LogFn {
16
+ <T extends object>(obj: T, msg?: string, ...args: any[]): void;
17
+ (obj: unknown, msg?: string, ...args: any[]): void;
18
+ (msg: string, ...args: any[]): void;
19
+ }
20
+ declare const loggerLevels: readonly ["trace", "debug", "info", "warn", "error", "fatal", "silent"];
21
+ export type LoggerLevel = (typeof loggerLevels)[number];
22
+ /**
23
+ * A simple logger class with various logging levels.
24
+ * @class
25
+ * @param {string} [level='info'] - Initial logging level.
26
+ * @param {ExternalLogger | undefined | null} [externalLogger=null] - Optional external logger to use.
27
+ */
28
+ export declare class SimpleLogger {
29
+ #private;
30
+ isExternal: boolean;
31
+ constructor(level?: LoggerLevel, externalLogger?: ExternalLogger);
32
+ trace: LogFn;
33
+ debug: LogFn;
34
+ info: LogFn;
35
+ warn: LogFn;
36
+ error: LogFn;
37
+ fatal: LogFn;
38
+ silent: LogFn;
39
+ /**
40
+ * Updates the logging methods based on the current logging level.
41
+ * @private
42
+ */
43
+ private updateLoggingMethods;
44
+ /**
45
+ * Checks if the provided logger is valid.
46
+ * @private
47
+ * @param {any} logger - The logger to check.
48
+ * @returns {boolean} - True if the logger is valid, otherwise false.
49
+ */
50
+ private isValidLogger;
51
+ /**
52
+ * Gets the external logger method for a specific level.
53
+ * @param {string} method - The logger method to get.
54
+ * @param {string} [fallbackMethod] - The fallback logger method to get.
55
+ * @returns {LoggerMethod} - The logger method or a no-op function.
56
+ * @private
57
+ */
58
+ private getExternalLoggerMethod;
59
+ /**
60
+ * Sets the logging level.
61
+ * @param {string} level - The logging level to set.
62
+ */
63
+ setLevel(level: string): void;
64
+ /**
65
+ * Sets an external logger to be used.
66
+ * @param {ExternalLogger | undefined | null} logger - The external logger to set.
67
+ */
68
+ setExternalLogger(logger: ExternalLogger | undefined | null, level?: LoggerLevel): void;
69
+ /**
70
+ * Logs the start of a function.
71
+ * @param {string} [functionName] - Optional function name to log.
72
+ */
73
+ logFunctionStart(functionName?: string): void;
74
+ /**
75
+ * Logs the end of a function.
76
+ * @param {string} [functionName] - Optional function name to log.
77
+ */
78
+ logFunctionEnd(functionName?: string): void;
79
+ }
80
+ export default SimpleLogger;
@@ -0,0 +1,152 @@
1
+ /**
2
+ * A module for simple logging with various logging levels.
3
+ * @module SimpleLogger
4
+ */
5
+ import { getCallerName } from 'vvlad1973-utils';
6
+ const loggerLevels = [
7
+ 'trace',
8
+ 'debug',
9
+ 'info',
10
+ 'warn',
11
+ 'error',
12
+ 'fatal',
13
+ 'silent',
14
+ ];
15
+ /**
16
+ * A simple logger class with various logging levels.
17
+ * @class
18
+ * @param {string} [level='info'] - Initial logging level.
19
+ * @param {ExternalLogger | undefined | null} [externalLogger=null] - Optional external logger to use.
20
+ */
21
+ export class SimpleLogger {
22
+ #levels = loggerLevels;
23
+ #currentLevel = 2;
24
+ #logger = console;
25
+ isExternal = false;
26
+ constructor(level, externalLogger) {
27
+ if (externalLogger && this.isValidLogger(externalLogger)) {
28
+ this.setExternalLogger(externalLogger, level);
29
+ }
30
+ else {
31
+ this.setLevel(level ?? 'info');
32
+ }
33
+ }
34
+ trace = (...args) => { };
35
+ debug = (...args) => { };
36
+ info = (...args) => { };
37
+ warn = (...args) => { };
38
+ error = (...args) => { };
39
+ fatal = (...args) => { };
40
+ silent = (...args) => { };
41
+ /**
42
+ * Updates the logging methods based on the current logging level.
43
+ * @private
44
+ */
45
+ updateLoggingMethods() {
46
+ try {
47
+ const noop = (...args) => { };
48
+ this.trace =
49
+ this.#currentLevel <= 0 ? this.getExternalLoggerMethod('trace') : noop;
50
+ this.debug =
51
+ this.#currentLevel <= 1 ? this.getExternalLoggerMethod('debug') : noop;
52
+ this.info =
53
+ this.#currentLevel <= 2 ? this.getExternalLoggerMethod('info') : noop;
54
+ this.warn =
55
+ this.#currentLevel <= 3 ? this.getExternalLoggerMethod('warn') : noop;
56
+ this.error =
57
+ this.#currentLevel <= 4 ? this.getExternalLoggerMethod('error') : noop;
58
+ this.fatal =
59
+ this.#currentLevel <= 5
60
+ ? this.getExternalLoggerMethod('fatal', 'error')
61
+ : noop;
62
+ this.silent = noop;
63
+ }
64
+ catch (error) {
65
+ console.error(error);
66
+ }
67
+ }
68
+ /**
69
+ * Checks if the provided logger is valid.
70
+ * @private
71
+ * @param {any} logger - The logger to check.
72
+ * @returns {boolean} - True if the logger is valid, otherwise false.
73
+ */
74
+ isValidLogger(logger) {
75
+ return loggerLevels.every((method) => {
76
+ return typeof logger[method] === 'function';
77
+ });
78
+ }
79
+ /**
80
+ * Gets the external logger method for a specific level.
81
+ * @param {string} method - The logger method to get.
82
+ * @param {string} [fallbackMethod] - The fallback logger method to get.
83
+ * @returns {LoggerMethod} - The logger method or a no-op function.
84
+ * @private
85
+ */
86
+ getExternalLoggerMethod(method, fallbackMethod) {
87
+ try {
88
+ const loggerMethod = this.#logger[method];
89
+ if (typeof loggerMethod === 'function') {
90
+ return loggerMethod.bind(this.#logger);
91
+ }
92
+ else if (typeof fallbackMethod !== 'undefined') {
93
+ const fallbackLoggerMethod = this.#logger[fallbackMethod];
94
+ if (typeof fallbackLoggerMethod === 'function') {
95
+ return fallbackLoggerMethod.bind(this.#logger);
96
+ }
97
+ }
98
+ return () => { };
99
+ }
100
+ catch (error) {
101
+ console.error(error);
102
+ return () => { };
103
+ }
104
+ }
105
+ /**
106
+ * Sets the logging level.
107
+ * @param {string} level - The logging level to set.
108
+ */
109
+ setLevel(level) {
110
+ const index = this.#levels.indexOf(level.toLowerCase());
111
+ if (index !== -1) {
112
+ this.#currentLevel = index;
113
+ if (typeof this.#logger.level === 'string') {
114
+ this.#logger.level = level;
115
+ }
116
+ this.updateLoggingMethods();
117
+ }
118
+ }
119
+ /**
120
+ * Sets an external logger to be used.
121
+ * @param {ExternalLogger | undefined | null} logger - The external logger to set.
122
+ */
123
+ setExternalLogger(logger, level) {
124
+ if (logger && this.isValidLogger(logger)) {
125
+ this.#logger = logger;
126
+ this.isExternal = true;
127
+ }
128
+ else {
129
+ this.#logger = console;
130
+ this.isExternal = false;
131
+ }
132
+ this.setLevel(level ?? logger?.level ?? this.#levels[this.#currentLevel]);
133
+ }
134
+ /**
135
+ * Logs the start of a function.
136
+ * @param {string} [functionName] - Optional function name to log.
137
+ */
138
+ logFunctionStart(functionName) {
139
+ const callerName = functionName || getCallerName();
140
+ this.trace(`Function start: ${callerName}`);
141
+ }
142
+ /**
143
+ * Logs the end of a function.
144
+ * @param {string} [functionName] - Optional function name to log.
145
+ */
146
+ logFunctionEnd(functionName) {
147
+ const callerName = functionName || getCallerName();
148
+ this.trace(`Function end: ${callerName}`);
149
+ }
150
+ }
151
+ export default SimpleLogger;
152
+ //# sourceMappingURL=simple-logger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"simple-logger.js","sourceRoot":"","sources":["../src/simple-logger.ts"],"names":[],"mappings":"AAAA;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C,aAAa,CAAC,MAAM,CAAC,EAAE,CAAC;YACzC,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;YACtB,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC;QACzB,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;YACvB,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC;QAC1B,CAAC;QACD,IAAI,CAAC,QAAQ,CAAC,KAAK,IAAI,MAAM,EAAE,KAAK,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC;IAC5E,CAAC;IAED;;;OAGG;IACI,gBAAgB,CAAC,YAAqB;QAC3C,MAAM,UAAU,GAAG,YAAY,IAAI,aAAa,EAAE,CAAC;QACnD,IAAI,CAAC,KAAK,CAAC,mBAAmB,UAAU,EAAE,CAAC,CAAC;IAC9C,CAAC;IAED;;;OAGG;IACI,cAAc,CAAC,YAAqB;QACzC,MAAM,UAAU,GAAG,YAAY,IAAI,aAAa,EAAE,CAAC;QACnD,IAAI,CAAC,KAAK,CAAC,iBAAiB,UAAU,EAAE,CAAC,CAAC;IAC5C,CAAC;CACF;AAED,eAAe,YAAY,CAAC"}
@@ -0,0 +1,129 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+
4
+ <head>
5
+
6
+ <meta charset="utf-8">
7
+ <meta name="viewport" content="width=device-width, initial-scale=1">
8
+ <title> Home</title>
9
+
10
+ <script src="https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js"></script>
11
+ <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
12
+ <script src="./build/entry.js"></script>
13
+ <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
14
+ <!--[if lt IE 9]>
15
+ <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
16
+ <![endif]-->
17
+ <link href="https://fonts.googleapis.com/css?family=Roboto:100,400,700|Inconsolata,700" rel="stylesheet">
18
+ <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
19
+ <link type="text/css" rel="stylesheet" href="https://jmblog.github.io/color-themes-for-google-code-prettify/themes/tomorrow-night.min.css">
20
+ <link type="text/css" rel="stylesheet" href="styles/app.min.css">
21
+ <link type="text/css" rel="stylesheet" href="styles/iframe.css">
22
+ <link type="text/css" rel="stylesheet" href="">
23
+ <script async defer src="https://buttons.github.io/buttons.js"></script>
24
+
25
+
26
+ </head>
27
+
28
+
29
+
30
+ <body class="layout small-header">
31
+ <div id="stickyNavbarOverlay"></div>
32
+
33
+
34
+ <div class="top-nav">
35
+ <div class="inner">
36
+ <a id="hamburger" role="button" class="navbar-burger" aria-label="menu" aria-expanded="false">
37
+ <span aria-hidden="true"></span>
38
+ <span aria-hidden="true"></span>
39
+ <span aria-hidden="true"></span>
40
+ </a>
41
+ <div class="logo">
42
+
43
+
44
+ </div>
45
+ <div class="menu">
46
+
47
+ <div class="navigation">
48
+ <a
49
+ href="index.html"
50
+ class="link"
51
+ >
52
+ Documentation
53
+ </a>
54
+
55
+
56
+
57
+ </div>
58
+ </div>
59
+ </div>
60
+ </div>
61
+ <div id="main">
62
+ <div
63
+ class="sidebar "
64
+ id="sidebarNav"
65
+ >
66
+
67
+ <nav>
68
+
69
+ <h2><a href="index.html">Documentation</a></h2><div class="category"><h3>Modules</h3><ul><li><a href="module-SimpleLogger.html">SimpleLogger</a></li></ul><h3>Classes</h3><ul><li><a href="module-SimpleLogger.SimpleLogger.html">SimpleLogger</a></li></ul></div>
70
+
71
+ </nav>
72
+ </div>
73
+ <div class="core" id="main-content-wrapper">
74
+ <div class="content">
75
+ <header class="page-title">
76
+ <p></p>
77
+ <h1>Home</h1>
78
+ </header>
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+ <h3> </h3>
87
+
88
+
89
+
90
+
91
+
92
+
93
+
94
+
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104
+
105
+
106
+
107
+ </div>
108
+
109
+ <footer class="footer">
110
+ <div class="content has-text-centered">
111
+ <p>Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 4.0.3</a></p>
112
+ <p class="sidebar-created-by">
113
+ <a href="https://github.com/SoftwareBrothers/better-docs" target="_blank">BetterDocs theme</a> provided with <i class="fas fa-heart"></i> by
114
+ <a href="http://softwarebrothers.co" target="_blank">SoftwareBrothers - JavaScript Development Agency</a>
115
+ </p>
116
+ </div>
117
+ </footer>
118
+
119
+ </div>
120
+ <div id="side-nav" class="side-nav">
121
+ </div>
122
+ </div>
123
+ <script src="scripts/app.min.js"></script>
124
+ <script>PR.prettyPrint();</script>
125
+ <script src="scripts/linenumber.js"> </script>
126
+
127
+
128
+ </body>
129
+ </html>