@ttoss/logger 0.6.11 → 0.7.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,119 +1,98 @@
1
1
  # @ttoss/logger
2
2
 
3
- A simple module to configure and send notifications to services like Discord from your applications.
3
+ Send notifications to Discord, Slack, or any custom endpoint from your applications.
4
4
 
5
5
  ## Installation
6
6
 
7
- Install the package via pnpm:
8
-
9
7
  ```bash
10
8
  pnpm add @ttoss/logger
11
9
  ```
12
10
 
13
- ## Usage
14
-
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.
16
-
17
- ### Configuration
18
-
19
- First, configure the logger with the necessary parameters, such as a Discord webhook URL:
11
+ ## Quick Start
20
12
 
21
13
  ```ts
22
- import { configureLogger } from '@ttoss/logger';
14
+ import { configureLogger, notify, log } from '@ttoss/logger';
23
15
 
16
+ // Configure once at app startup
24
17
  configureLogger({
25
- discordWebhookUrl: 'https://discord.com/api/webhooks/your-webhook-here',
26
- project: 'My project',
18
+ project: 'My App',
19
+ discordWebhookUrl: 'https://discord.com/api/webhooks/xxx',
27
20
  });
28
- ```
29
-
30
- ### Sending Notifications
31
21
 
32
- Use the `notify` method to send messages to the configured services:
33
-
34
- ```ts
35
- import { notify } from '@ttoss/logger';
22
+ // Send notifications
23
+ await notify({ type: 'error', message: 'Something went wrong!' });
24
+ await notify({ type: 'info', title: 'Deploy', message: 'v1.2.0 released' });
36
25
 
37
- await notify({
38
- type: 'error',
39
- message: 'Hello! This is a notification for Discord.',
40
- });
26
+ // Local console logging
27
+ log.info('Server started');
28
+ log.warn('High memory usage');
29
+ log.error('Database connection failed');
41
30
  ```
42
31
 
43
- ### Local Logging
32
+ ## Custom Endpoints
44
33
 
45
- For console logs, use the `log` object:
34
+ Send notifications to any platform by providing a custom formatter:
46
35
 
47
36
  ```ts
48
- import { log } from '@ttoss/logger';
37
+ configureLogger({
38
+ project: 'My App',
39
+ discordWebhookUrl: 'https://discord.com/api/webhooks/xxx',
40
+ customEndpoints: [
41
+ {
42
+ url: 'https://hooks.slack.com/services/xxx',
43
+ formatBody: ({ notification, project }) => ({
44
+ text: `[${project}] ${notification.type}: ${notification.message}`,
45
+ }),
46
+ },
47
+ {
48
+ url: 'https://my-api.com/alerts',
49
+ headers: { Authorization: 'Bearer token' },
50
+ method: 'PUT',
51
+ formatBody: ({ notification }) => ({
52
+ severity: notification.type,
53
+ message: notification.message,
54
+ }),
55
+ },
56
+ ],
57
+ });
58
+ ```
49
59
 
50
- log.info('Useful information');
60
+ ### CustomEndpoint Options
51
61
 
52
- log.warn('Important warning');
53
-
54
- log.error('Critical error');
55
- ```
62
+ | Property | Type | Description |
63
+ | ------------ | ---------------------------- | ------------------------------------------------------------------ |
64
+ | `url` | `string` | Endpoint URL (required) |
65
+ | `formatBody` | `function` | Formats the request body (required) |
66
+ | `headers` | `Record<string, string>` | Custom headers (default: `{ 'Content-Type': 'application/json' }`) |
67
+ | `method` | `'POST' \| 'PUT' \| 'PATCH'` | HTTP method (default: `'POST'`) |
68
+ | `name` | `string` | Optional identifier for debugging |
56
69
 
57
70
  ## API
58
71
 
59
- ### `configureLogger(params)`
60
-
61
- Configures the logger with notification sending options.
72
+ ### `configureLogger(config)`
62
73
 
63
- - **Parameters**:
64
- - `params.discordWebhookUrl` (string): The Discord webhook URL.
65
- - `params.project` (string): The project identifier to prefix notifications.
74
+ | Parameter | Type | Description |
75
+ | ------------------- | ------------------------------------ | ------------------------------------- |
76
+ | `project` | `string` | Project name for notification context |
77
+ | `discordWebhookUrl` | `string` | Discord webhook URL |
78
+ | `customEndpoints` | `CustomEndpoint \| CustomEndpoint[]` | Custom notification endpoints |
66
79
 
67
80
  ### `notify(notification)`
68
81
 
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
87
-
88
- ```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
98
-
99
- await notify({
100
- type: 'info',
101
- message: 'Application started successfully!',
102
- });
82
+ | Parameter | Type | Description |
83
+ | --------- | ----------------------------- | --------------------- |
84
+ | `type` | `'info' \| 'warn' \| 'error'` | Notification severity |
85
+ | `message` | `string` | Notification content |
86
+ | `title` | `string` | Optional title |
87
+ | `log` | `boolean` | Also log to console |
103
88
 
104
- // Local logs
89
+ ### `notifyError({ error, title?, log? })`
105
90
 
106
- log.info('Starting the server...');
91
+ Convenience method for error notifications that extracts the message from Error objects.
107
92
 
108
- log.warn('Low memory.');
109
-
110
- log.error('Failed to connect to the database.');
111
- ```
112
-
113
- ## Notes
93
+ ### `log`
114
94
 
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.
95
+ Console logging methods: `log.info()`, `log.warn()`, `log.error()`
117
96
 
118
97
  ## License
119
98
 
package/dist/esm/index.js CHANGED
@@ -39,6 +39,30 @@ var sendNotificationToDiscord = /* @__PURE__ */__name(async ({
39
39
  body
40
40
  });
41
41
  }, "sendNotificationToDiscord");
42
+ var sendToCustomEndpoint = /* @__PURE__ */__name(async ({
43
+ notification,
44
+ endpoint,
45
+ project
46
+ }) => {
47
+ const body = endpoint.formatBody({
48
+ notification,
49
+ project
50
+ });
51
+ await fetch(endpoint.url, {
52
+ method: endpoint.method || "POST",
53
+ headers: {
54
+ "Content-Type": "application/json",
55
+ ...(endpoint.headers ?? {})
56
+ },
57
+ body: JSON.stringify(body)
58
+ });
59
+ }, "sendToCustomEndpoint");
60
+ var getCustomEndpointsArray = /* @__PURE__ */__name(endpoints => {
61
+ if (!endpoints) {
62
+ return [];
63
+ }
64
+ return Array.isArray(endpoints) ? endpoints : [endpoints];
65
+ }, "getCustomEndpointsArray");
42
66
  var notify = /* @__PURE__ */__name(async notification => {
43
67
  if (notification.log) {
44
68
  const message = [notification.title, notification.message].join(": ");
@@ -47,13 +71,23 @@ var notify = /* @__PURE__ */__name(async notification => {
47
71
  if (!setup?.project) {
48
72
  return;
49
73
  }
74
+ const promises = [];
50
75
  if (setup?.discordWebhookUrl) {
51
- await sendNotificationToDiscord({
76
+ promises.push(sendNotificationToDiscord({
52
77
  notification,
53
78
  url: setup.discordWebhookUrl,
54
79
  project: setup.project
55
- });
80
+ }));
81
+ }
82
+ const customEndpoints = getCustomEndpointsArray(setup.customEndpoints);
83
+ for (const endpoint of customEndpoints) {
84
+ promises.push(sendToCustomEndpoint({
85
+ notification,
86
+ endpoint,
87
+ project: setup.project
88
+ }));
56
89
  }
90
+ await Promise.all(promises);
57
91
  }, "notify");
58
92
  var getErrorMessage = /* @__PURE__ */__name(error => {
59
93
  if (error instanceof Error) {
@@ -72,4 +106,4 @@ var notifyError = /* @__PURE__ */__name(async notification => {
72
106
  log: notification.log
73
107
  });
74
108
  }, "notifyError");
75
- export { configureLogger, log, notify, notifyError, sendNotificationToDiscord };
109
+ export { configureLogger, log, notify, notifyError };
package/dist/index.d.mts CHANGED
@@ -19,16 +19,47 @@ type NotificationMessage = {
19
19
  message: string;
20
20
  log?: boolean;
21
21
  };
22
+ /**
23
+ * Custom endpoint configuration for sending notifications to any platform.
24
+ */
25
+ type CustomEndpoint = {
26
+ /**
27
+ * The URL of the endpoint to send notifications to.
28
+ */
29
+ url: string;
30
+ /**
31
+ * Optional name to identify this endpoint (useful for debugging).
32
+ */
33
+ name?: string;
34
+ /**
35
+ * Function to format the notification message for this specific endpoint.
36
+ * Receives the notification and project name, returns a plain object to be JSON serialized as the request body.
37
+ * Must return a value of type Record<string, unknown>.
38
+ */
39
+ formatBody: (params: {
40
+ notification: NotificationMessage;
41
+ project: string;
42
+ }) => Record<string, unknown>;
43
+ /**
44
+ * Optional custom headers for the request.
45
+ * Defaults to { 'Content-Type': 'application/json' }
46
+ */
47
+ headers?: Record<string, string>;
48
+ /**
49
+ * HTTP method to use. Defaults to 'POST'.
50
+ */
51
+ method?: 'POST' | 'PUT' | 'PATCH';
52
+ };
22
53
  type Configuration = {
23
54
  discordWebhookUrl?: string;
24
55
  project?: string;
56
+ /**
57
+ * Custom endpoints to send notifications to.
58
+ * Can be a single endpoint or an array of endpoints.
59
+ */
60
+ customEndpoints?: CustomEndpoint | CustomEndpoint[];
25
61
  };
26
62
  declare const configureLogger: (params: Configuration) => void;
27
- declare const sendNotificationToDiscord: ({ notification, url, project, }: {
28
- notification: NotificationMessage;
29
- url: string;
30
- project: string;
31
- }) => Promise<void>;
32
63
  declare const notify: (notification: NotificationMessage) => Promise<void>;
33
64
  declare const notifyError: (notification: {
34
65
  error: unknown;
@@ -36,4 +67,4 @@ declare const notifyError: (notification: {
36
67
  log?: boolean;
37
68
  }) => Promise<void>;
38
69
 
39
- export { configureLogger, log, notify, notifyError, sendNotificationToDiscord };
70
+ export { type CustomEndpoint, configureLogger, log, notify, notifyError };
package/dist/index.d.ts CHANGED
@@ -19,16 +19,47 @@ type NotificationMessage = {
19
19
  message: string;
20
20
  log?: boolean;
21
21
  };
22
+ /**
23
+ * Custom endpoint configuration for sending notifications to any platform.
24
+ */
25
+ type CustomEndpoint = {
26
+ /**
27
+ * The URL of the endpoint to send notifications to.
28
+ */
29
+ url: string;
30
+ /**
31
+ * Optional name to identify this endpoint (useful for debugging).
32
+ */
33
+ name?: string;
34
+ /**
35
+ * Function to format the notification message for this specific endpoint.
36
+ * Receives the notification and project name, returns a plain object to be JSON serialized as the request body.
37
+ * Must return a value of type Record<string, unknown>.
38
+ */
39
+ formatBody: (params: {
40
+ notification: NotificationMessage;
41
+ project: string;
42
+ }) => Record<string, unknown>;
43
+ /**
44
+ * Optional custom headers for the request.
45
+ * Defaults to { 'Content-Type': 'application/json' }
46
+ */
47
+ headers?: Record<string, string>;
48
+ /**
49
+ * HTTP method to use. Defaults to 'POST'.
50
+ */
51
+ method?: 'POST' | 'PUT' | 'PATCH';
52
+ };
22
53
  type Configuration = {
23
54
  discordWebhookUrl?: string;
24
55
  project?: string;
56
+ /**
57
+ * Custom endpoints to send notifications to.
58
+ * Can be a single endpoint or an array of endpoints.
59
+ */
60
+ customEndpoints?: CustomEndpoint | CustomEndpoint[];
25
61
  };
26
62
  declare const configureLogger: (params: Configuration) => void;
27
- declare const sendNotificationToDiscord: ({ notification, url, project, }: {
28
- notification: NotificationMessage;
29
- url: string;
30
- project: string;
31
- }) => Promise<void>;
32
63
  declare const notify: (notification: NotificationMessage) => Promise<void>;
33
64
  declare const notifyError: (notification: {
34
65
  error: unknown;
@@ -36,4 +67,4 @@ declare const notifyError: (notification: {
36
67
  log?: boolean;
37
68
  }) => Promise<void>;
38
69
 
39
- export { configureLogger, log, notify, notifyError, sendNotificationToDiscord };
70
+ export { type CustomEndpoint, configureLogger, log, notify, notifyError };
package/dist/index.js CHANGED
@@ -34,8 +34,7 @@ __export(index_exports, {
34
34
  configureLogger: () => configureLogger,
35
35
  log: () => log,
36
36
  notify: () => notify,
37
- notifyError: () => notifyError,
38
- sendNotificationToDiscord: () => sendNotificationToDiscord
37
+ notifyError: () => notifyError
39
38
  });
40
39
  module.exports = __toCommonJS(index_exports);
41
40
  var log = {
@@ -71,6 +70,30 @@ var sendNotificationToDiscord = /* @__PURE__ */__name(async ({
71
70
  body
72
71
  });
73
72
  }, "sendNotificationToDiscord");
73
+ var sendToCustomEndpoint = /* @__PURE__ */__name(async ({
74
+ notification,
75
+ endpoint,
76
+ project
77
+ }) => {
78
+ const body = endpoint.formatBody({
79
+ notification,
80
+ project
81
+ });
82
+ await fetch(endpoint.url, {
83
+ method: endpoint.method || "POST",
84
+ headers: {
85
+ "Content-Type": "application/json",
86
+ ...(endpoint.headers ?? {})
87
+ },
88
+ body: JSON.stringify(body)
89
+ });
90
+ }, "sendToCustomEndpoint");
91
+ var getCustomEndpointsArray = /* @__PURE__ */__name(endpoints => {
92
+ if (!endpoints) {
93
+ return [];
94
+ }
95
+ return Array.isArray(endpoints) ? endpoints : [endpoints];
96
+ }, "getCustomEndpointsArray");
74
97
  var notify = /* @__PURE__ */__name(async notification => {
75
98
  if (notification.log) {
76
99
  const message = [notification.title, notification.message].join(": ");
@@ -79,13 +102,23 @@ var notify = /* @__PURE__ */__name(async notification => {
79
102
  if (!setup?.project) {
80
103
  return;
81
104
  }
105
+ const promises = [];
82
106
  if (setup?.discordWebhookUrl) {
83
- await sendNotificationToDiscord({
107
+ promises.push(sendNotificationToDiscord({
84
108
  notification,
85
109
  url: setup.discordWebhookUrl,
86
110
  project: setup.project
87
- });
111
+ }));
112
+ }
113
+ const customEndpoints = getCustomEndpointsArray(setup.customEndpoints);
114
+ for (const endpoint of customEndpoints) {
115
+ promises.push(sendToCustomEndpoint({
116
+ notification,
117
+ endpoint,
118
+ project: setup.project
119
+ }));
88
120
  }
121
+ await Promise.all(promises);
89
122
  }, "notify");
90
123
  var getErrorMessage = /* @__PURE__ */__name(error => {
91
124
  if (error instanceof Error) {
@@ -109,6 +142,5 @@ var notifyError = /* @__PURE__ */__name(async notification => {
109
142
  configureLogger,
110
143
  log,
111
144
  notify,
112
- notifyError,
113
- sendNotificationToDiscord
145
+ notifyError
114
146
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ttoss/logger",
3
- "version": "0.6.11",
3
+ "version": "0.7.0",
4
4
  "description": "A simple module to configure and send notifications to services like Discord from your applications.",
5
5
  "license": "MIT",
6
6
  "contributors": [],
@@ -23,8 +23,8 @@
23
23
  "devDependencies": {
24
24
  "jest": "^30.2.0",
25
25
  "tsup": "^8.5.1",
26
- "@ttoss/config": "^1.35.12",
27
- "@ttoss/test-utils": "^4.0.0"
26
+ "@ttoss/test-utils": "^4.0.1",
27
+ "@ttoss/config": "^1.35.12"
28
28
  },
29
29
  "keywords": [],
30
30
  "publishConfig": {