jet-logger 2.0.1 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,116 +1,12 @@
1
- # Jet-Logger
2
-
3
- > A super quick, easy to setup logging tool for NodeJS/TypeScript.
4
-
5
-
6
- ## What is it
7
- jet-logger is an easy to configure logging tool that allows you change settings via the environment variables (recommended) or manually in code. You can easily switch your logs to be printed out to the command line, written in a file, sent through your own custom logging logic, or turned off completely. Logs printed to the console also are printed out in different colors depending on whether they're info, a warning, an error, etc. The file for holding logs can be specified manually or left as the default. You can also have logs formatted as lines for easy reading or as JSON objects.
8
- <br/>
9
-
10
- ### Installation
11
- ```batch
12
- $ npm install --save jet-logger
13
- ```
14
-
15
- ### Guide
16
- The logger package's default export is an instance of the `JetLogger` class. This default export uses all the default settings. If you wish to pass your own settings you can import the `JetLogger` class and pass parameters to the constructor to configure your own custom logger.
17
-
18
- - The five environment variables are:
19
- - `JET_LOGGER_MODE`: can be `'CONSOLE'`(default), `'FILE'`, `'CUSTOM'`, and `'OFF'`.
20
- - `JET_LOGGER_FILEPATH`: the file-path for file mode. Default is `_home_dir/jet-logger.log_`.
21
- - `JET_LOGGER_FILEPATH_DATETIME`: prepend the log file name with the datetime. Can be `'TRUE'` (default) or `'FALSE'`.
22
- - `JET_LOGGER_TIMESTAMP`: adds a timestamp next to each log. Can be `'TRUE'` (default) or `'FALSE'`.
23
- - `JET_LOGGER_FORMAT`: formats log as a line or JSON object. Can be `'LINE'` (default) or `'JSON'`.
24
-
25
- _logger_ has an export `LoggerModes` which is an enum that provides all the modes if you want to use them in code. I would recommend using `Console` for local development, `File` for remote development, and `Custom` or `Off` for production. If you want to change the settings in code, you can do so via importing the `JetLogger` class and calling it with whatever options you want.
26
- <br>
27
-
28
- - There are 4 functions on Logger to print logs.
29
- - `info`: prints green.
30
- - `imp`: prints magenta.
31
- - `warn`: prints yellow.
32
- - `err`: prints red.
33
-
34
- There is an optional second param to each method which is a `boolean`. If you pass `true` as the second param, JetLogger will use node's `util` so that the full object gets printed. You should NOT normally use this param, but it is especially useful when debugging errors so that you can print out the full error object and observe the stack trace.<br>
35
-
36
- Let's look at some sample code in an express route.
37
-
38
-
39
- ````typescript
40
- /* Some script that is run before the route script */
41
-
42
- // Apply logger settings (Note you could also using a tool "dotenv" to set env variables)
43
- // These must be set before logger is imported
44
- const logFilePath = path.join(__dirname, '../sampleProject.log');
45
- process.env.JET_LOGGER_MODE = LoggerModes.File; // Can also be Console, Custom, or Off
46
- process.env.JET_LOGGER_FILEPATH = logFilePath;
47
-
48
-
49
- /* In you route script */
50
-
51
- import { OK } from 'http-status-codes';
52
- import { Router, Request, Response } from 'express';
53
- import logger from 'jet-logger';
54
-
55
-
56
- const router = Router();
57
-
58
- router.get('api/users/alt', async (req: Request, res: Reponse) => {
59
- logger.info(req.params.msg);
60
- logger.imp(req.params.msg);
61
- logger.warn(req.params.msg);
62
- logger.err(req.params.msg);
63
- logger.err(new Error('printing out an error'));
64
- logger.err(new Error('printing out an error full'), true); // <-- print the full Error object
65
- return res.status(OK).json({
66
- message: 'console_mode',
67
- });
68
- });
69
- ````
70
-
71
-
72
- - The previous code-snippet will show the following content when printed:
73
- ````
74
- [2020-10-11T04:50:59.339Z] INFO: hello jet-logger
75
- [2020-10-11T04:50:59.341Z] IMPORTANT: hello jet-logger
76
- [2020-10-11T04:50:59.341Z] WARNING: hello jet-logger
77
- [2020-10-11T04:50:59.342Z] ERROR: hello jet-logger
78
- [2020-10-11T04:50:59.372Z] ERROR: Error: Demo print full error object
79
- at Object.<anonymous> (C:\Projects\jet-logger\sample-project\src\index.ts:21:12)
80
- at Module._compile (internal/modules/cjs/loader.js:956:30)
81
- at Module.m._compile (C:\Users\seanp\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:536:23)
82
- at Module._extensions..js (internal/modules/cjs/loader.js:973:10)
83
- at Object.require.extensions.<computed> [as .ts] (C:\Users\seanp\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:539:12)
84
- at Module.load (internal/modules/cjs/loader.js:812:32)
85
- at Function.Module._load (internal/modules/cjs/loader.js:724:14)
86
- at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
87
- at main (C:\Users\seanp\AppData\Roaming\npm\node_modules\ts-node\src\bin.ts:212:14)
88
- at Object.<anonymous> (C:\Users\seanp\AppData\Roaming\npm\node_modules\ts-node\src\bin.ts:470:3)
89
- ````
90
-
91
-
92
- ### Using a custom logger
93
- For production you'll probably have some third party logging tool like ElasticSearch or Splunk. _logger_ exports a type `TCustomLogFn` that needs to implemented. If you implement this function and pass it to JetLogger and set the mode to `CUSTOM`, Logger will call whatever logic you created for it.
94
-
95
-
96
- ````typescript
97
- // In the route file
98
- import { OK } from 'http-status-codes';
99
- import { Router, Request, Response } from 'express';
100
- import { JetLogger, TCustomLogFn } from 'jet-logger';
101
- import { thirdPartyLoggingApp } from 'thirdPartyLoggingApplicationLib';
102
-
103
-
104
- // Needs to be implemented
105
- const customSend: TCustomLogFn = (timestamp: Date, level: string, content: unknown) => {
106
- thirdPartyLoggingApp.doStuff(...);
107
- }
108
-
109
- router.get('api/users', async (req: Request, res: Reponse) => {
110
- const logger = new JetLogger(LoggerModes.CUSTOM, '', true, true, undefined, customSend);
111
- logger.info(req.params.msg);
112
- return res.status(OK).json({
113
- message: 'console_mode',
114
- });
115
- });
116
- ````
1
+ # Jet-Logger ✈️
2
+
3
+ > Super fast, zero-dependency logging for Node.js and TypeScript projects.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/jet-logger?logo=npm&label=npm)](https://www.npmjs.com/package/jet-logger)
6
+ [![npm downloads](https://img.shields.io/npm/dm/jet-logger?color=orange)](https://www.npmjs.com/package/jet-logger)
7
+ [![License](https://img.shields.io/npm/l/jet-logger)](https://github.com/seanpmaxwell/jet-logger/blob/master/LICENSE)
8
+ [![TypeScript definitions](https://img.shields.io/badge/TypeScript-ready-3178c6?logo=typescript&logoColor=white)](https://www.npmjs.com/package/jet-logger)
9
+
10
+ Jet-Logger is an easy-to-configure logger that can print to the console, write to disk, or forward events to your own transport. Configure it entirely through environment variables or in code, and get colorized output, timestamps, and JSON log formatting out-of-the-box.
11
+
12
+ Please refer to the official <a href="https://github.com/seanpmaxwell/jet-logger">github repo</a> for the most up-to-date documentation.
@@ -0,0 +1,239 @@
1
+ /* eslint-disable no-process-env */
2
+ import util from 'util';
3
+ import colors from 'colors';
4
+ import fs from 'fs';
5
+ /******************************************************************************
6
+ Variables
7
+ ******************************************************************************/
8
+ // Options for printing a log.
9
+ export const LoggerModes = {
10
+ Console: 'CONSOLE',
11
+ File: 'FILE',
12
+ Custom: 'CUSTOM',
13
+ Off: 'OFF',
14
+ };
15
+ // Log formats
16
+ export const Formats = {
17
+ Line: 'LINE',
18
+ Json: 'JSON',
19
+ };
20
+ // Note colors here need be a color from
21
+ // the colors library above.
22
+ const Levels = {
23
+ Info: {
24
+ Color: 'green',
25
+ Prefix: 'INFO',
26
+ },
27
+ Important: {
28
+ Color: 'magenta',
29
+ Prefix: 'IMPORTANT',
30
+ },
31
+ Warning: {
32
+ Color: 'yellow',
33
+ Prefix: 'WARNING',
34
+ },
35
+ Error: {
36
+ Color: 'red',
37
+ Prefix: 'ERROR',
38
+ },
39
+ };
40
+ // Errors
41
+ const Errors = {
42
+ CustomLogFn: 'Custom logger mode set to true, but no custom logger was ' + 'provided.',
43
+ Mode: 'The correct logger mode was not specified: Must be "CUSTOM", ' +
44
+ '"FILE", "OFF", or "CONSOLE".',
45
+ };
46
+ /******************************************************************************
47
+ Classes
48
+ ******************************************************************************/
49
+ export class JetLogger {
50
+ mode = LoggerModes.Console;
51
+ filePath = 'jet-logger.log';
52
+ timestamp = true;
53
+ format = Formats.Line;
54
+ customLogFn = () => ({});
55
+ /**
56
+ * Constructor
57
+ */
58
+ constructor(mode, filepath, filepathDatetimeParam, timestamp, format, customLogFn) {
59
+ // Setup the mode
60
+ if (mode !== undefined) {
61
+ this.mode = mode;
62
+ }
63
+ else if (!!process.env.JET_LOGGER_MODE) {
64
+ this.mode = process.env.JET_LOGGER_MODE.toUpperCase();
65
+ }
66
+ // Filepath
67
+ if (filepath !== undefined) {
68
+ this.filePath = filepath;
69
+ }
70
+ else if (!!process.env.JET_LOGGER_FILEPATH) {
71
+ this.filePath = process.env.JET_LOGGER_FILEPATH;
72
+ }
73
+ // FilePath dateTime
74
+ let filePathDatetime = true;
75
+ if (filepathDatetimeParam !== undefined) {
76
+ filePathDatetime = filepathDatetimeParam;
77
+ }
78
+ else if (!!process.env.JET_LOGGER_FILEPATH_DATETIME) {
79
+ const envVar = process.env.JET_LOGGER_FILEPATH_DATETIME;
80
+ filePathDatetime = envVar.toUpperCase() === 'TRUE';
81
+ }
82
+ // Timestamp
83
+ if (timestamp !== undefined) {
84
+ this.timestamp = timestamp;
85
+ }
86
+ else if (!!process.env.JET_LOGGER_TIMESTAMP) {
87
+ const envVar = process.env.JET_LOGGER_TIMESTAMP;
88
+ this.timestamp = envVar.toUpperCase() === 'TRUE';
89
+ }
90
+ // Format
91
+ if (format !== undefined) {
92
+ this.format = format;
93
+ }
94
+ else if (!!process.env.JET_LOGGER_FORMAT) {
95
+ this.format = process.env.JET_LOGGER_FORMAT.toUpperCase();
96
+ }
97
+ // Modify filepath if filepath datetime is true
98
+ if (filePathDatetime) {
99
+ this.filePath = this.addDatetimeToFileName(this.filePath);
100
+ }
101
+ // Custom Logger Function
102
+ if (customLogFn !== undefined) {
103
+ this.customLogFn = customLogFn;
104
+ }
105
+ }
106
+ /**
107
+ * Prepend the filename in the file path with a timestamp.
108
+ * i.e. '/home/jet-logger.log' => '/home/20220805T033709_jet-logger.log'
109
+ */
110
+ addDatetimeToFileName(filePath) {
111
+ // Get the date string
112
+ const dateStr = new Date()
113
+ .toISOString()
114
+ .split('-')
115
+ .join('')
116
+ .split(':')
117
+ .join('')
118
+ .slice(0, 15);
119
+ // Setup new file name
120
+ const filePathArr = filePath.split('/'), lastIdx = filePathArr.length - 1, fileName = filePathArr[lastIdx], fileNameNew = dateStr + '_' + fileName;
121
+ // Setup new file path
122
+ filePathArr[lastIdx] = fileNameNew;
123
+ return filePathArr.join('/');
124
+ }
125
+ /**
126
+ * Print information.
127
+ */
128
+ info(content, printFull) {
129
+ this.printLog(content, !!printFull, Levels.Info);
130
+ }
131
+ /**
132
+ * Print important information.
133
+ */
134
+ imp(content, printFull) {
135
+ this.printLog(content, !!printFull, Levels.Important);
136
+ }
137
+ /**
138
+ * Print important information.
139
+ */
140
+ warn(content, printFull) {
141
+ this.printLog(content, !!printFull, Levels.Warning);
142
+ }
143
+ /**
144
+ * Print important information.
145
+ */
146
+ err(content, printFull) {
147
+ this.printLog(content, !!printFull, Levels.Error);
148
+ }
149
+ /**
150
+ * Print the log using the provided settings.
151
+ */
152
+ printLog(contentParam, printFull, level) {
153
+ // Do nothing if turned off
154
+ if (this.mode === LoggerModes.Off) {
155
+ return;
156
+ }
157
+ // Print full
158
+ let content;
159
+ if (printFull) {
160
+ content = util.inspect(contentParam);
161
+ }
162
+ else {
163
+ content = String(contentParam);
164
+ }
165
+ // Fire the custom logger if that's the option
166
+ if (this.mode === LoggerModes.Custom) {
167
+ if (!!this.customLogFn) {
168
+ return this.customLogFn(new Date(), level.Prefix, content);
169
+ }
170
+ else {
171
+ throw Error(Errors.CustomLogFn);
172
+ }
173
+ }
174
+ // Print line or json
175
+ if (this.format === Formats.Line) {
176
+ content = this.setupLineFormat(content, level);
177
+ }
178
+ else if (this.format === Formats.Json) {
179
+ content = this.setupJsonFormat(content, level);
180
+ }
181
+ // Print Console
182
+ if (this.mode === LoggerModes.Console) {
183
+ const colorFn = colors[level.Color];
184
+ // eslint-disable-next-line no-console
185
+ console.log(colorFn(content));
186
+ // Print File
187
+ }
188
+ else if (this.mode === LoggerModes.File) {
189
+ this.writeToFile(content + '\n');
190
+ // If reach this point, mode setting was bad
191
+ }
192
+ else {
193
+ throw Error(Errors.Mode);
194
+ }
195
+ }
196
+ /**
197
+ * Setup line format.
198
+ */
199
+ setupLineFormat(content, level) {
200
+ // Format
201
+ content = level.Prefix + ': ' + content;
202
+ if (this.timestamp) {
203
+ const time = '[' + new Date().toISOString() + '] ';
204
+ return time + content;
205
+ }
206
+ // Return
207
+ return content;
208
+ }
209
+ /**
210
+ * Setup json format.
211
+ */
212
+ setupJsonFormat(content, level) {
213
+ // Format
214
+ const json = {
215
+ level: level.Prefix,
216
+ message: content,
217
+ };
218
+ if (this.timestamp) {
219
+ json.timestamp = new Date().toISOString();
220
+ }
221
+ // Return
222
+ return JSON.stringify(json);
223
+ }
224
+ /**
225
+ * Write to file.
226
+ */
227
+ writeToFile(content) {
228
+ fs.appendFile(this.filePath, content, (err) => {
229
+ if (!!err) {
230
+ // eslint-disable-next-line no-console
231
+ console.error(err);
232
+ }
233
+ });
234
+ }
235
+ }
236
+ /******************************************************************************
237
+ Export
238
+ ******************************************************************************/
239
+ export default new JetLogger();
@@ -0,0 +1 @@
1
+ export { LoggerModes, Formats, JetLogger, default as default, } from './JetLogger.js';
@@ -0,0 +1,239 @@
1
+ /* eslint-disable no-process-env */
2
+ import util from 'util';
3
+ import colors from 'colors';
4
+ import fs from 'fs';
5
+ /******************************************************************************
6
+ Variables
7
+ ******************************************************************************/
8
+ // Options for printing a log.
9
+ export const LoggerModes = {
10
+ Console: 'CONSOLE',
11
+ File: 'FILE',
12
+ Custom: 'CUSTOM',
13
+ Off: 'OFF',
14
+ };
15
+ // Log formats
16
+ export const Formats = {
17
+ Line: 'LINE',
18
+ Json: 'JSON',
19
+ };
20
+ // Note colors here need be a color from
21
+ // the colors library above.
22
+ const Levels = {
23
+ Info: {
24
+ Color: 'green',
25
+ Prefix: 'INFO',
26
+ },
27
+ Important: {
28
+ Color: 'magenta',
29
+ Prefix: 'IMPORTANT',
30
+ },
31
+ Warning: {
32
+ Color: 'yellow',
33
+ Prefix: 'WARNING',
34
+ },
35
+ Error: {
36
+ Color: 'red',
37
+ Prefix: 'ERROR',
38
+ },
39
+ };
40
+ // Errors
41
+ const Errors = {
42
+ CustomLogFn: 'Custom logger mode set to true, but no custom logger was ' + 'provided.',
43
+ Mode: 'The correct logger mode was not specified: Must be "CUSTOM", ' +
44
+ '"FILE", "OFF", or "CONSOLE".',
45
+ };
46
+ /******************************************************************************
47
+ Classes
48
+ ******************************************************************************/
49
+ export class JetLogger {
50
+ mode = LoggerModes.Console;
51
+ filePath = 'jet-logger.log';
52
+ timestamp = true;
53
+ format = Formats.Line;
54
+ customLogFn = () => ({});
55
+ /**
56
+ * Constructor
57
+ */
58
+ constructor(mode, filepath, filepathDatetimeParam, timestamp, format, customLogFn) {
59
+ // Setup the mode
60
+ if (mode !== undefined) {
61
+ this.mode = mode;
62
+ }
63
+ else if (!!process.env.JET_LOGGER_MODE) {
64
+ this.mode = process.env.JET_LOGGER_MODE.toUpperCase();
65
+ }
66
+ // Filepath
67
+ if (filepath !== undefined) {
68
+ this.filePath = filepath;
69
+ }
70
+ else if (!!process.env.JET_LOGGER_FILEPATH) {
71
+ this.filePath = process.env.JET_LOGGER_FILEPATH;
72
+ }
73
+ // FilePath dateTime
74
+ let filePathDatetime = true;
75
+ if (filepathDatetimeParam !== undefined) {
76
+ filePathDatetime = filepathDatetimeParam;
77
+ }
78
+ else if (!!process.env.JET_LOGGER_FILEPATH_DATETIME) {
79
+ const envVar = process.env.JET_LOGGER_FILEPATH_DATETIME;
80
+ filePathDatetime = envVar.toUpperCase() === 'TRUE';
81
+ }
82
+ // Timestamp
83
+ if (timestamp !== undefined) {
84
+ this.timestamp = timestamp;
85
+ }
86
+ else if (!!process.env.JET_LOGGER_TIMESTAMP) {
87
+ const envVar = process.env.JET_LOGGER_TIMESTAMP;
88
+ this.timestamp = envVar.toUpperCase() === 'TRUE';
89
+ }
90
+ // Format
91
+ if (format !== undefined) {
92
+ this.format = format;
93
+ }
94
+ else if (!!process.env.JET_LOGGER_FORMAT) {
95
+ this.format = process.env.JET_LOGGER_FORMAT.toUpperCase();
96
+ }
97
+ // Modify filepath if filepath datetime is true
98
+ if (filePathDatetime) {
99
+ this.filePath = this.addDatetimeToFileName(this.filePath);
100
+ }
101
+ // Custom Logger Function
102
+ if (customLogFn !== undefined) {
103
+ this.customLogFn = customLogFn;
104
+ }
105
+ }
106
+ /**
107
+ * Prepend the filename in the file path with a timestamp.
108
+ * i.e. '/home/jet-logger.log' => '/home/20220805T033709_jet-logger.log'
109
+ */
110
+ addDatetimeToFileName(filePath) {
111
+ // Get the date string
112
+ const dateStr = new Date()
113
+ .toISOString()
114
+ .split('-')
115
+ .join('')
116
+ .split(':')
117
+ .join('')
118
+ .slice(0, 15);
119
+ // Setup new file name
120
+ const filePathArr = filePath.split('/'), lastIdx = filePathArr.length - 1, fileName = filePathArr[lastIdx], fileNameNew = dateStr + '_' + fileName;
121
+ // Setup new file path
122
+ filePathArr[lastIdx] = fileNameNew;
123
+ return filePathArr.join('/');
124
+ }
125
+ /**
126
+ * Print information.
127
+ */
128
+ info(content, printFull) {
129
+ this.printLog(content, !!printFull, Levels.Info);
130
+ }
131
+ /**
132
+ * Print important information.
133
+ */
134
+ imp(content, printFull) {
135
+ this.printLog(content, !!printFull, Levels.Important);
136
+ }
137
+ /**
138
+ * Print important information.
139
+ */
140
+ warn(content, printFull) {
141
+ this.printLog(content, !!printFull, Levels.Warning);
142
+ }
143
+ /**
144
+ * Print important information.
145
+ */
146
+ err(content, printFull) {
147
+ this.printLog(content, !!printFull, Levels.Error);
148
+ }
149
+ /**
150
+ * Print the log using the provided settings.
151
+ */
152
+ printLog(contentParam, printFull, level) {
153
+ // Do nothing if turned off
154
+ if (this.mode === LoggerModes.Off) {
155
+ return;
156
+ }
157
+ // Print full
158
+ let content;
159
+ if (printFull) {
160
+ content = util.inspect(contentParam);
161
+ }
162
+ else {
163
+ content = String(contentParam);
164
+ }
165
+ // Fire the custom logger if that's the option
166
+ if (this.mode === LoggerModes.Custom) {
167
+ if (!!this.customLogFn) {
168
+ return this.customLogFn(new Date(), level.Prefix, content);
169
+ }
170
+ else {
171
+ throw Error(Errors.CustomLogFn);
172
+ }
173
+ }
174
+ // Print line or json
175
+ if (this.format === Formats.Line) {
176
+ content = this.setupLineFormat(content, level);
177
+ }
178
+ else if (this.format === Formats.Json) {
179
+ content = this.setupJsonFormat(content, level);
180
+ }
181
+ // Print Console
182
+ if (this.mode === LoggerModes.Console) {
183
+ const colorFn = colors[level.Color];
184
+ // eslint-disable-next-line no-console
185
+ console.log(colorFn(content));
186
+ // Print File
187
+ }
188
+ else if (this.mode === LoggerModes.File) {
189
+ this.writeToFile(content + '\n');
190
+ // If reach this point, mode setting was bad
191
+ }
192
+ else {
193
+ throw Error(Errors.Mode);
194
+ }
195
+ }
196
+ /**
197
+ * Setup line format.
198
+ */
199
+ setupLineFormat(content, level) {
200
+ // Format
201
+ content = level.Prefix + ': ' + content;
202
+ if (this.timestamp) {
203
+ const time = '[' + new Date().toISOString() + '] ';
204
+ return time + content;
205
+ }
206
+ // Return
207
+ return content;
208
+ }
209
+ /**
210
+ * Setup json format.
211
+ */
212
+ setupJsonFormat(content, level) {
213
+ // Format
214
+ const json = {
215
+ level: level.Prefix,
216
+ message: content,
217
+ };
218
+ if (this.timestamp) {
219
+ json.timestamp = new Date().toISOString();
220
+ }
221
+ // Return
222
+ return JSON.stringify(json);
223
+ }
224
+ /**
225
+ * Write to file.
226
+ */
227
+ writeToFile(content) {
228
+ fs.appendFile(this.filePath, content, (err) => {
229
+ if (!!err) {
230
+ // eslint-disable-next-line no-console
231
+ console.error(err);
232
+ }
233
+ });
234
+ }
235
+ }
236
+ /******************************************************************************
237
+ Export
238
+ ******************************************************************************/
239
+ export default new JetLogger();
@@ -0,0 +1 @@
1
+ export { LoggerModes, Formats, JetLogger, default as default, } from './JetLogger.js';
@@ -0,0 +1,75 @@
1
+ /******************************************************************************
2
+ Variables
3
+ ******************************************************************************/
4
+ export declare const LoggerModes: {
5
+ readonly Console: "CONSOLE";
6
+ readonly File: "FILE";
7
+ readonly Custom: "CUSTOM";
8
+ readonly Off: "OFF";
9
+ };
10
+ export declare const Formats: {
11
+ readonly Line: "LINE";
12
+ readonly Json: "JSON";
13
+ };
14
+ /******************************************************************************
15
+ Types
16
+ ******************************************************************************/
17
+ type TLoggerModes = (typeof LoggerModes)[keyof typeof LoggerModes];
18
+ type TFormats = (typeof Formats)[keyof typeof Formats];
19
+ export type TCustomLoggerFunction = (timestamp: Date, prefix: string, content: unknown) => void;
20
+ /******************************************************************************
21
+ Classes
22
+ ******************************************************************************/
23
+ export declare class JetLogger {
24
+ private mode;
25
+ private filePath;
26
+ private timestamp;
27
+ private format;
28
+ private customLogFn;
29
+ /**
30
+ * Constructor
31
+ */
32
+ constructor(mode?: TLoggerModes, filepath?: string, filepathDatetimeParam?: boolean, timestamp?: boolean, format?: TFormats, customLogFn?: TCustomLoggerFunction);
33
+ /**
34
+ * Prepend the filename in the file path with a timestamp.
35
+ * i.e. '/home/jet-logger.log' => '/home/20220805T033709_jet-logger.log'
36
+ */
37
+ private addDatetimeToFileName;
38
+ /**
39
+ * Print information.
40
+ */
41
+ info(content: unknown, printFull?: boolean): void;
42
+ /**
43
+ * Print important information.
44
+ */
45
+ imp(content: unknown, printFull?: boolean): void;
46
+ /**
47
+ * Print important information.
48
+ */
49
+ warn(content: unknown, printFull?: boolean): void;
50
+ /**
51
+ * Print important information.
52
+ */
53
+ err(content: unknown, printFull?: boolean): void;
54
+ /**
55
+ * Print the log using the provided settings.
56
+ */
57
+ private printLog;
58
+ /**
59
+ * Setup line format.
60
+ */
61
+ private setupLineFormat;
62
+ /**
63
+ * Setup json format.
64
+ */
65
+ private setupJsonFormat;
66
+ /**
67
+ * Write to file.
68
+ */
69
+ private writeToFile;
70
+ }
71
+ /******************************************************************************
72
+ Export
73
+ ******************************************************************************/
74
+ declare const _default: JetLogger;
75
+ export default _default;
@@ -0,0 +1 @@
1
+ export { LoggerModes, Formats, type TCustomLoggerFunction, JetLogger, default as default, } from './JetLogger.js';
package/package.json CHANGED
@@ -1,15 +1,31 @@
1
1
  {
2
2
  "name": "jet-logger",
3
- "version": "2.0.1",
3
+ "version": "2.1.1",
4
4
  "description": "A super quick, easy to setup logging tool for NodeJS/TypeScript.",
5
- "main": "./lib/index.js",
6
- "typings": "./lib/index.d.ts",
7
- "directories": {
8
- "lib": "lib"
5
+ "type": "module",
6
+ "main": "./dist/cjs/index.js",
7
+ "module": "./dist/esm/index.js",
8
+ "browser": "./dist/esm/index.js",
9
+ "types": "./dist/types/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "import": "./dist/esm/index.js",
13
+ "require": "./dist/cjs/index.js",
14
+ "types": "./dist/types/index.d.ts"
15
+ }
9
16
  },
17
+ "files": [
18
+ "dist"
19
+ ],
10
20
  "scripts": {
11
- "test": "npx ts-node ./test",
12
- "build": "tsc -p tsconfig.build.json"
21
+ "build": "rm -rf ./dist && tsc -p tsconfig.esm.json && tsc -p tsconfig.cjs.json && tsc -p tsconfig.types.json",
22
+ "clean-install": "rm -rf ./node_modules && rm -r package-lock.json && npm i",
23
+ "lint": "eslint .",
24
+ "format": "eslint --fix .",
25
+ "playground": "tsx ./test/playground.ts",
26
+ "pre-publish": "mv README.md README-git && mv README-npm README.md",
27
+ "post-publish": "mv README.md README-npm && mv README-git README.md",
28
+ "test": "NODE_ENV=test vitest"
13
29
  },
14
30
  "repository": {
15
31
  "type": "git",
@@ -20,25 +36,21 @@
20
36
  "logging",
21
37
  "log",
22
38
  "console",
23
- "print",
24
39
  "node",
25
40
  "nodejs",
26
- "overnight",
27
- "overnightjs",
28
- "overnightjs/logger",
29
- "winston",
41
+ "node.js",
42
+ "typescript",
43
+ "ts",
44
+ "typescript-logger",
45
+ "typescript-logging",
46
+ "node-logger",
47
+ "node-logging",
30
48
  "jet",
49
+ "jet-logger",
50
+ "jetlogger",
31
51
  "simple",
32
52
  "easy",
33
- "quick",
34
- "jet-logger",
35
- "best",
36
- "type",
37
- "typescript",
38
- "script",
39
- "env",
40
- "environment",
41
- "variables"
53
+ "quick"
42
54
  ],
43
55
  "author": "sean maxwell",
44
56
  "license": "MIT",
@@ -50,34 +62,18 @@
50
62
  "colors": "1.3.0"
51
63
  },
52
64
  "devDependencies": {
53
- "@types/node": "^14.11.8",
54
- "@typescript-eslint/eslint-plugin": "^4.4.0",
55
- "@typescript-eslint/parser": "^4.4.0",
56
- "eslint": "^7.11.0",
57
- "typescript": "^4.0.3"
58
- },
59
- "eslintConfig": {
60
- "parser": "@typescript-eslint/parser",
61
- "plugins": [
62
- "@typescript-eslint"
63
- ],
64
- "extends": [
65
- "eslint:recommended",
66
- "plugin:@typescript-eslint/recommended",
67
- "plugin:@typescript-eslint/recommended-requiring-type-checking"
68
- ],
69
- "parserOptions": {
70
- "project": "./tsconfig.json"
71
- },
72
- "rules": {
73
- "no-console": 0,
74
- "no-extra-boolean-cast": 0,
75
- "@typescript-eslint/restrict-plus-operands": 0,
76
- "@typescript-eslint/explicit-module-boundary-types": 0,
77
- "@typescript-eslint/no-explicit-any": 0,
78
- "@typescript-eslint/no-unsafe-member-access": 0,
79
- "@typescript-eslint/no-unsafe-call": 0,
80
- "@typescript-eslint/no-unsafe-assignment": 0
81
- }
65
+ "@eslint/js": "^9.26.0",
66
+ "@stylistic/eslint-plugin": "^5.6.1",
67
+ "@types/node": "^22.8.1",
68
+ "eslint": "^9.26.0",
69
+ "eslint-config-prettier": "^10.1.8",
70
+ "eslint-plugin-n": "^17.17.0",
71
+ "eslint-plugin-prettier": "^5.5.4",
72
+ "jiti": "^2.3.3",
73
+ "prettier": "^3.7.4",
74
+ "typescript": "~5.9.3",
75
+ "tsx": "^4.19.1",
76
+ "typescript-eslint": "^8.50.0",
77
+ "vitest": "^4.0.15"
82
78
  }
83
79
  }
@@ -1,30 +0,0 @@
1
- export declare enum LoggerModes {
2
- Console = "CONSOLE",
3
- File = "FILE",
4
- Custom = "CUSTOM",
5
- Off = "OFF"
6
- }
7
- export declare enum Formats {
8
- Line = "LINE",
9
- Json = "JSON"
10
- }
11
- export declare type TCustomLogFn = (timestamp: Date, prefix: string, content: unknown) => void;
12
- export declare class JetLogger {
13
- private mode;
14
- private filePath;
15
- private timestamp;
16
- private format;
17
- private customLogFn;
18
- constructor(mode?: LoggerModes, filepath?: string, filepathDatetimeParam?: boolean, timestamp?: boolean, format?: Formats, customLogFn?: TCustomLogFn);
19
- private addDatetimeToFileName;
20
- info(content: unknown, printFull?: boolean): void;
21
- imp(content: unknown, printFull?: boolean): void;
22
- warn(content: unknown, printFull?: boolean): void;
23
- err(content: unknown, printFull?: boolean): void;
24
- private printLog;
25
- private setupLineFormat;
26
- private setupJsonFormat;
27
- private writeToFile;
28
- }
29
- declare const _default: JetLogger;
30
- export default _default;
package/lib/JetLogger.js DELETED
@@ -1,178 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.JetLogger = exports.Formats = exports.LoggerModes = void 0;
7
- var util_1 = __importDefault(require("util"));
8
- var colors_1 = __importDefault(require("colors"));
9
- var fs_1 = __importDefault(require("fs"));
10
- var LoggerModes;
11
- (function (LoggerModes) {
12
- LoggerModes["Console"] = "CONSOLE";
13
- LoggerModes["File"] = "FILE";
14
- LoggerModes["Custom"] = "CUSTOM";
15
- LoggerModes["Off"] = "OFF";
16
- })(LoggerModes = exports.LoggerModes || (exports.LoggerModes = {}));
17
- var Formats;
18
- (function (Formats) {
19
- Formats["Line"] = "LINE";
20
- Formats["Json"] = "JSON";
21
- })(Formats = exports.Formats || (exports.Formats = {}));
22
- var Levels = {
23
- Info: {
24
- Color: 'green',
25
- Prefix: 'INFO',
26
- },
27
- Important: {
28
- Color: 'magenta',
29
- Prefix: 'IMPORTANT',
30
- },
31
- Warning: {
32
- Color: 'yellow',
33
- Prefix: 'WARNING',
34
- },
35
- Error: {
36
- Color: 'red',
37
- Prefix: 'ERROR',
38
- }
39
- };
40
- var Errors = {
41
- CustomLogFn: 'Custom logger mode set to true, but no custom logger was ' +
42
- 'provided.',
43
- Mode: 'The correct logger mode was not specified: Must be "CUSTOM", ' +
44
- '"FILE", "OFF", or "CONSOLE".'
45
- };
46
- var JetLogger = (function () {
47
- function JetLogger(mode, filepath, filepathDatetimeParam, timestamp, format, customLogFn) {
48
- this.mode = LoggerModes.Console;
49
- this.filePath = 'jet-logger.log';
50
- this.timestamp = true;
51
- this.format = Formats.Line;
52
- this.customLogFn = function () { return ({}); };
53
- if (mode !== undefined) {
54
- this.mode = mode;
55
- }
56
- else if (!!process.env.JET_LOGGER_MODE) {
57
- this.mode = process.env.JET_LOGGER_MODE.toUpperCase();
58
- }
59
- if (filepath !== undefined) {
60
- this.filePath = filepath;
61
- }
62
- else if (!!process.env.JET_LOGGER_FILEPATH) {
63
- this.filePath = process.env.JET_LOGGER_FILEPATH;
64
- }
65
- var filePathDatetime = true;
66
- if (filepathDatetimeParam !== undefined) {
67
- filePathDatetime = filepathDatetimeParam;
68
- }
69
- else if (!!process.env.JET_LOGGER_FILEPATH_DATETIME) {
70
- var envVar = process.env.JET_LOGGER_FILEPATH_DATETIME;
71
- filePathDatetime = envVar.toUpperCase() === 'TRUE';
72
- }
73
- if (timestamp !== undefined) {
74
- this.timestamp = timestamp;
75
- }
76
- else if (!!process.env.JET_LOGGER_TIMESTAMP) {
77
- var envVar = process.env.JET_LOGGER_TIMESTAMP;
78
- this.timestamp = (envVar.toUpperCase() === 'TRUE');
79
- }
80
- if (format !== undefined) {
81
- this.format = format;
82
- }
83
- else if (!!process.env.JET_LOGGER_FORMAT) {
84
- this.format = process.env.JET_LOGGER_FORMAT.toUpperCase();
85
- }
86
- if (filePathDatetime) {
87
- this.filePath = this.addDatetimeToFileName(this.filePath);
88
- }
89
- if (customLogFn !== undefined) {
90
- this.customLogFn = customLogFn;
91
- }
92
- }
93
- JetLogger.prototype.addDatetimeToFileName = function (filePath) {
94
- var dateStr = new Date().toISOString()
95
- .split('-').join('')
96
- .split(':').join('')
97
- .slice(0, 15);
98
- var filePathArr = filePath.split('/'), lastIdx = filePathArr.length - 1, fileName = filePathArr[lastIdx], fileNameNew = (dateStr + '_' + fileName);
99
- filePathArr[lastIdx] = fileNameNew;
100
- return filePathArr.join('/');
101
- };
102
- JetLogger.prototype.info = function (content, printFull) {
103
- this.printLog(content, !!printFull, Levels.Info);
104
- };
105
- JetLogger.prototype.imp = function (content, printFull) {
106
- this.printLog(content, !!printFull, Levels.Important);
107
- };
108
- JetLogger.prototype.warn = function (content, printFull) {
109
- this.printLog(content, !!printFull, Levels.Warning);
110
- };
111
- JetLogger.prototype.err = function (content, printFull) {
112
- this.printLog(content, !!printFull, Levels.Error);
113
- };
114
- JetLogger.prototype.printLog = function (contentParam, printFull, level) {
115
- if (this.mode === LoggerModes.Off) {
116
- return;
117
- }
118
- var content;
119
- if (printFull) {
120
- content = util_1.default.inspect(contentParam);
121
- }
122
- else {
123
- content = String(contentParam);
124
- }
125
- if (this.mode === LoggerModes.Custom) {
126
- if (!!this.customLogFn) {
127
- return this.customLogFn(new Date(), level.Prefix, content);
128
- }
129
- else {
130
- throw Error(Errors.CustomLogFn);
131
- }
132
- }
133
- if (this.format === Formats.Line) {
134
- content = this.setupLineFormat(content, level);
135
- }
136
- else if (this.format === Formats.Json) {
137
- content = this.setupJsonFormat(content, level);
138
- }
139
- if (this.mode === LoggerModes.Console) {
140
- var colorFn = colors_1.default[level.Color];
141
- console.log(colorFn(content));
142
- }
143
- else if (this.mode === LoggerModes.File) {
144
- this.writeToFile(content + '\n');
145
- }
146
- else {
147
- throw Error(Errors.Mode);
148
- }
149
- };
150
- JetLogger.prototype.setupLineFormat = function (content, level) {
151
- content = (level.Prefix + ': ' + content);
152
- if (this.timestamp) {
153
- var time = '[' + new Date().toISOString() + '] ';
154
- return (time + content);
155
- }
156
- return content;
157
- };
158
- JetLogger.prototype.setupJsonFormat = function (content, level) {
159
- var json = {
160
- level: level.Prefix,
161
- message: content,
162
- };
163
- if (this.timestamp) {
164
- json.timestamp = new Date().toISOString();
165
- }
166
- return JSON.stringify(json);
167
- };
168
- JetLogger.prototype.writeToFile = function (content) {
169
- fs_1.default.appendFile(this.filePath, content, function (err) {
170
- if (!!err) {
171
- console.error(err);
172
- }
173
- });
174
- };
175
- return JetLogger;
176
- }());
177
- exports.JetLogger = JetLogger;
178
- exports.default = new JetLogger();
package/lib/index.d.ts DELETED
@@ -1 +0,0 @@
1
- export { LoggerModes, Formats, TCustomLogFn, JetLogger, default as default, } from './JetLogger';
package/lib/index.js DELETED
@@ -1,11 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.default = exports.JetLogger = exports.Formats = exports.LoggerModes = void 0;
7
- var JetLogger_1 = require("./JetLogger");
8
- Object.defineProperty(exports, "LoggerModes", { enumerable: true, get: function () { return JetLogger_1.LoggerModes; } });
9
- Object.defineProperty(exports, "Formats", { enumerable: true, get: function () { return JetLogger_1.Formats; } });
10
- Object.defineProperty(exports, "JetLogger", { enumerable: true, get: function () { return JetLogger_1.JetLogger; } });
11
- Object.defineProperty(exports, "default", { enumerable: true, get: function () { return __importDefault(JetLogger_1).default; } });