@ttoss/logger 0.3.17 → 0.5.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.
package/README.md CHANGED
@@ -1,57 +1,120 @@
1
1
  # @ttoss/logger
2
2
 
3
- Simple environment agnostic logger.
3
+ A simple module to configure and send notifications to services like Discord from your applications.
4
4
 
5
- ## Motivation
5
+ ## Installation
6
6
 
7
- Often, for debugging some piece of code, developers use console.log for it. When the application goes for production, some of these logs still appears, most because they forget to clear these logs.
8
- These package solves this, providing some levels of log that are emitted based on the environment of the application.
7
+ Install the package via pnpm:
9
8
 
10
- ## Log Levels vs Environments
9
+ ```bash
10
+ pnpm add @ttoss/logger
11
+ ```
12
+
13
+ ## Usage
11
14
 
12
- <table>
13
- <thead>
14
- <tr><th>Log Level</th><th>Environment</th></tr>
15
- </thead>
16
- <tbody>
17
- <tr><td>Warn</td><td>Dev-only</td></tr>
18
- <tr><td>Error</td><td>All</td></tr>
19
- <tr><td>Info</td><td>Dev-only</td></tr>
20
- </tbody>
21
- </table>
15
+ The `@ttoss/logger` module allows you to configure a logger and send notifications to external services, such as Discord, with ease. It also provides basic methods for local console logging.
22
16
 
23
- ## How to use
17
+ ### Configuration
24
18
 
25
- Just instantiate the logger, providing the `isDev` value configuration and start to use:
19
+ First, configure the logger with the necessary parameters, such as a Discord webhook URL:
26
20
 
27
21
  ```ts
28
- // createLogger.ts
22
+ import { configureLogger } from '@ttoss/logger';
23
+
24
+ configureLogger({
25
+ discordWebhookUrl: 'https://discord.com/api/webhooks/your-webhook-here',
26
+ project: 'My project',
27
+ });
28
+ ```
29
29
 
30
- import { Logger } from '@ttoss/logger';
31
- import { config } from 'dotenv';
30
+ ### Sending Notifications
32
31
 
33
- config();
32
+ Use the `notify` method to send messages to the configured services:
34
33
 
35
- export const createLogger = Logger(process.env.DEV === 'true');
34
+ ```ts
35
+ import { notify } from '@ttoss/logger';
36
+
37
+ await notify({
38
+ type: 'error',
39
+ message: 'Hello! This is a notification for Discord.',
40
+ });
41
+ ```
36
42
 
37
- // randomFile.ts
43
+ ### Local Logging
38
44
 
39
- const logger = createLogger('randomFile');
45
+ For console logs, use the `log` object:
40
46
 
41
- logger.warn('This will emit an warn on console');
47
+ ```ts
48
+ import { log } from '@ttoss/logger';
42
49
 
43
- logger.error('This will emit a log of type error on console');
50
+ log.info('Useful information');
44
51
 
45
- loggger.info('This will emit a simple log on console');
52
+ log.warn('Important warning');
53
+
54
+ log.error('Critical error');
46
55
  ```
47
56
 
48
- If you not pass any parameter to `Logger`, it gonna considers to be in dev environment:
57
+ ## API
58
+
59
+ ### `configureLogger(params)`
60
+
61
+ Configures the logger with notification sending options.
62
+
63
+ - **Parameters**:
64
+ - `params.discordWebhookUrl` (string): The Discord webhook URL.
65
+ - `params.project` (string): The project identifier to prefix notifications.
66
+
67
+ ### `notify(notification)`
68
+
69
+ Sends a notification to the configured services.
70
+
71
+ - **Parameters**:
72
+ - `notification` (object): The notification to send, with the following properties:
73
+ - `type` ('info' | 'warn' | 'error'): The type of the notification.
74
+ - `title` (string, optional): The title of the notification.
75
+ - `message` (string): The main message content.
76
+ - **Returns**: A Promise that resolves when the sending is complete.
77
+
78
+ ### `log`
79
+
80
+ Object with methods for local logging:
81
+
82
+ - `log.warn(message)`: Displays a warning in the console.
83
+ - `log.error(message)`: Displays an error in the console.
84
+ - `log.info(message)`: Displays an info message in the console.
85
+
86
+ ## Complete Example
49
87
 
50
88
  ```ts
51
- // createLogger.ts
89
+ import { configureLogger, notify, log } from '@ttoss/logger';
90
+
91
+ // Configure the logger
92
+
93
+ configureLogger({
94
+ discordWebhookUrl: 'https://discord.com/api/webhooks/your-webhook-here',
95
+ });
96
+
97
+ // Send a notification
52
98
 
53
- import { Logger } from '@ttoss/logger';
99
+ await notify({
100
+ type: 'info',
101
+ message: 'Application started successfully!',
102
+ });
54
103
 
55
- // In dev environment, gonna log everything
56
- export const createLogger = Logger();
104
+ // Local logs
105
+
106
+ log.info('Starting the server...');
107
+
108
+ log.warn('Low memory.');
109
+
110
+ log.error('Failed to connect to the database.');
57
111
  ```
112
+
113
+ ## Notes
114
+
115
+ - Currently, support is limited to Discord via webhooks, but more services will be added in the future.
116
+ - Ensure the `discordWebhookUrl` is valid to avoid silent failures.
117
+
118
+ ## License
119
+
120
+ [MIT](https://github.com/ttoss/ttoss/blob/main/LICENSE)
package/dist/esm/index.js CHANGED
@@ -1,32 +1,49 @@
1
1
  /** Powered by @ttoss/config. https://ttoss.dev/docs/modules/packages/config/ */
2
2
 
3
3
  // src/index.ts
4
- var {
5
- log,
6
- warn,
7
- error
8
- } = console;
9
- var Logger = isDev => {
10
- const devEnv = isDev !== void 0 ? isDev : true;
11
- return prefix => {
12
- return {
13
- warn: value => {
14
- if (devEnv) {
15
- const now = /* @__PURE__ */new Date();
16
- warn(`[${now}] - ${prefix} - ${value}`);
17
- }
18
- },
19
- info: value => {
20
- if (devEnv) {
21
- const now = /* @__PURE__ */new Date();
22
- log(`[${now}] - ${prefix} - ${value}`);
23
- }
24
- },
25
- error: value => {
26
- const now = /* @__PURE__ */new Date();
27
- error(`[${now}] - ${prefix} - ${value}`);
4
+ var setup = null;
5
+ var configureLogger = params => {
6
+ setup = params;
7
+ };
8
+ var sendNotificationToDiscord = async ({
9
+ notification,
10
+ url,
11
+ project
12
+ }) => {
13
+ const embedMessage = {
14
+ embeds: [{
15
+ title: notification.title || `${notification.type.toUpperCase()} from ${project}`,
16
+ description: notification.message,
17
+ color: notification.type === "error" ? 16711680 : notification.type === "warn" ? 16776960 : 65280,
18
+ footer: {
19
+ text: `Project: ${project}`
28
20
  }
29
- };
21
+ }]
30
22
  };
23
+ const body = JSON.stringify(embedMessage);
24
+ await fetch(url, {
25
+ method: "POST",
26
+ headers: {
27
+ "Content-Type": "application/json"
28
+ },
29
+ body
30
+ });
31
+ };
32
+ var notify = async notification => {
33
+ if (!setup?.project) {
34
+ return;
35
+ }
36
+ if (setup?.discordWebhookUrl) {
37
+ await sendNotificationToDiscord({
38
+ notification,
39
+ url: setup.discordWebhookUrl,
40
+ project: setup.project
41
+ });
42
+ }
43
+ };
44
+ var log = {
45
+ warn: console.warn,
46
+ error: console.error,
47
+ info: console.info
31
48
  };
32
- export { Logger };
49
+ export { configureLogger, log, notify, sendNotificationToDiscord };
package/dist/index.d.mts CHANGED
@@ -1,7 +1,33 @@
1
- declare const Logger: (isDev?: boolean) => (prefix: string) => {
2
- warn: (value: string) => void;
3
- info: (value: string) => void;
4
- error: (value: string) => void;
1
+ type NotificationType = 'info' | 'warn' | 'error';
2
+ type NotificationMessage = {
3
+ type: NotificationType;
4
+ title?: string;
5
+ message: string;
6
+ };
7
+ type Configuration = {
8
+ discordWebhookUrl?: string;
9
+ project?: string;
10
+ };
11
+ declare const configureLogger: (params: Configuration) => void;
12
+ declare const sendNotificationToDiscord: ({ notification, url, project, }: {
13
+ notification: NotificationMessage;
14
+ url: string;
15
+ project: string;
16
+ }) => Promise<void>;
17
+ declare const notify: (notification: NotificationMessage) => Promise<void>;
18
+ declare const log: {
19
+ warn: {
20
+ (...data: any[]): void;
21
+ (message?: any, ...optionalParams: any[]): void;
22
+ };
23
+ error: {
24
+ (...data: any[]): void;
25
+ (message?: any, ...optionalParams: any[]): void;
26
+ };
27
+ info: {
28
+ (...data: any[]): void;
29
+ (message?: any, ...optionalParams: any[]): void;
30
+ };
5
31
  };
6
32
 
7
- export { Logger };
33
+ export { configureLogger, log, notify, sendNotificationToDiscord };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,33 @@
1
- declare const Logger: (isDev?: boolean) => (prefix: string) => {
2
- warn: (value: string) => void;
3
- info: (value: string) => void;
4
- error: (value: string) => void;
1
+ type NotificationType = 'info' | 'warn' | 'error';
2
+ type NotificationMessage = {
3
+ type: NotificationType;
4
+ title?: string;
5
+ message: string;
6
+ };
7
+ type Configuration = {
8
+ discordWebhookUrl?: string;
9
+ project?: string;
10
+ };
11
+ declare const configureLogger: (params: Configuration) => void;
12
+ declare const sendNotificationToDiscord: ({ notification, url, project, }: {
13
+ notification: NotificationMessage;
14
+ url: string;
15
+ project: string;
16
+ }) => Promise<void>;
17
+ declare const notify: (notification: NotificationMessage) => Promise<void>;
18
+ declare const log: {
19
+ warn: {
20
+ (...data: any[]): void;
21
+ (message?: any, ...optionalParams: any[]): void;
22
+ };
23
+ error: {
24
+ (...data: any[]): void;
25
+ (message?: any, ...optionalParams: any[]): void;
26
+ };
27
+ info: {
28
+ (...data: any[]): void;
29
+ (message?: any, ...optionalParams: any[]): void;
30
+ };
5
31
  };
6
32
 
7
- export { Logger };
33
+ export { configureLogger, log, notify, sendNotificationToDiscord };
package/dist/index.js CHANGED
@@ -27,38 +27,61 @@ var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
27
27
  // src/index.ts
28
28
  var index_exports = {};
29
29
  __export(index_exports, {
30
- Logger: () => Logger
30
+ configureLogger: () => configureLogger,
31
+ log: () => log,
32
+ notify: () => notify,
33
+ sendNotificationToDiscord: () => sendNotificationToDiscord
31
34
  });
32
35
  module.exports = __toCommonJS(index_exports);
33
- var {
34
- log,
35
- warn,
36
- error
37
- } = console;
38
- var Logger = isDev => {
39
- const devEnv = isDev !== void 0 ? isDev : true;
40
- return prefix => {
41
- return {
42
- warn: value => {
43
- if (devEnv) {
44
- const now = /* @__PURE__ */new Date();
45
- warn(`[${now}] - ${prefix} - ${value}`);
46
- }
47
- },
48
- info: value => {
49
- if (devEnv) {
50
- const now = /* @__PURE__ */new Date();
51
- log(`[${now}] - ${prefix} - ${value}`);
52
- }
53
- },
54
- error: value => {
55
- const now = /* @__PURE__ */new Date();
56
- error(`[${now}] - ${prefix} - ${value}`);
36
+ var setup = null;
37
+ var configureLogger = params => {
38
+ setup = params;
39
+ };
40
+ var sendNotificationToDiscord = async ({
41
+ notification,
42
+ url,
43
+ project
44
+ }) => {
45
+ const embedMessage = {
46
+ embeds: [{
47
+ title: notification.title || `${notification.type.toUpperCase()} from ${project}`,
48
+ description: notification.message,
49
+ color: notification.type === "error" ? 16711680 : notification.type === "warn" ? 16776960 : 65280,
50
+ footer: {
51
+ text: `Project: ${project}`
57
52
  }
58
- };
53
+ }]
59
54
  };
55
+ const body = JSON.stringify(embedMessage);
56
+ await fetch(url, {
57
+ method: "POST",
58
+ headers: {
59
+ "Content-Type": "application/json"
60
+ },
61
+ body
62
+ });
63
+ };
64
+ var notify = async notification => {
65
+ if (!setup?.project) {
66
+ return;
67
+ }
68
+ if (setup?.discordWebhookUrl) {
69
+ await sendNotificationToDiscord({
70
+ notification,
71
+ url: setup.discordWebhookUrl,
72
+ project: setup.project
73
+ });
74
+ }
75
+ };
76
+ var log = {
77
+ warn: console.warn,
78
+ error: console.error,
79
+ info: console.info
60
80
  };
61
81
  // Annotate the CommonJS export names for ESM import in node:
62
82
  0 && (module.exports = {
63
- Logger
83
+ configureLogger,
84
+ log,
85
+ notify,
86
+ sendNotificationToDiscord
64
87
  });
package/package.json CHANGED
@@ -1,11 +1,9 @@
1
1
  {
2
2
  "name": "@ttoss/logger",
3
- "version": "0.3.17",
4
- "description": "Simple environment agnostic logger",
3
+ "version": "0.5.0",
4
+ "description": "A simple module to configure and send notifications to services like Discord from your applications.",
5
5
  "license": "MIT",
6
- "contributors": [
7
- "Eron Alves <eron.alves@rocketmail.com>"
8
- ],
6
+ "contributors": [],
9
7
  "repository": {
10
8
  "type": "git",
11
9
  "url": "https://github.com/ttoss/ttoss.git",
@@ -18,12 +16,12 @@
18
16
  "types": "./dist/index.d.ts"
19
17
  }
20
18
  },
21
- "module": "dist/esm/index.js",
22
19
  "files": [
23
20
  "dist"
24
21
  ],
25
22
  "sideEffects": false,
26
23
  "devDependencies": {
24
+ "jest": "^29.7.0",
27
25
  "tsup": "^8.3.5",
28
26
  "@ttoss/config": "^1.35.2"
29
27
  },
@@ -33,6 +31,7 @@
33
31
  "provenance": true
34
32
  },
35
33
  "scripts": {
36
- "build": "tsup"
34
+ "build": "tsup",
35
+ "test": "jest --projects tests/unit"
37
36
  }
38
37
  }