astro-logger-sdk 1.0.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 ADDED
@@ -0,0 +1,106 @@
1
+ # logger-sdk
2
+
3
+ Official SDK for sending logs to your AppLogger platform.
4
+
5
+ ---
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install astro-logger-sdk
11
+ ```
12
+
13
+ ---
14
+
15
+ ## Usage
16
+
17
+ ### CommonJS
18
+
19
+ ```js
20
+ const logger = require("astro-logger-sdk");
21
+
22
+ logger.init({
23
+ apiKey: "ak_your_api_key_here",
24
+ appName: "my-app",
25
+ baseUrl: "https://your-api.com",
26
+ });
27
+
28
+ const result = await logger.log({ message: "Server started", level: "INFO" });
29
+ ```
30
+
31
+ ### ES Modules
32
+
33
+ ```js
34
+ import { init, log } from "astro-logger-sdk";
35
+
36
+ init({
37
+ apiKey: "ak_your_api_key_here",
38
+ appName: "my-app",
39
+ baseUrl: "https://your-api.com",
40
+ });
41
+
42
+ const result = await log({ message: "Server started", level: "INFO" });
43
+ ```
44
+
45
+ ---
46
+
47
+ ## API
48
+
49
+ ### `init({ apiKey, appName, baseUrl })`
50
+
51
+ Must be called once before using `log()`.
52
+
53
+ | Parameter | Type | Required | Description |
54
+ | --------- | ------ | -------- | ----------------------------------------- |
55
+ | apiKey | string | ✅ | Your developer API key from the dashboard |
56
+ | appName | string | ✅ | Your application's unique name |
57
+ | baseUrl | string | ✅ | Base URL of the logging server |
58
+
59
+ ---
60
+
61
+ ### `log({ message, level })`
62
+
63
+ Sends a log entry to the server. Returns a result object — never throws.
64
+
65
+ | Parameter | Type | Required | Description |
66
+ | --------- | ------ | -------- | ------------------------------- |
67
+ | message | string | ✅ | The log message |
68
+ | level | string | ✅ | One of: `INFO`, `WARN`, `ERROR` |
69
+
70
+ #### Success response
71
+
72
+ ```js
73
+ { success: true, data: { _id, message, level, count, createdAt, updatedAt, ... } }
74
+ ```
75
+
76
+ #### Error response
77
+
78
+ ```js
79
+ { success: false, status: 403, error: '[logger-sdk] Forbidden: ...' }
80
+ ```
81
+
82
+ ---
83
+
84
+ ## Handling results
85
+
86
+ `log()` never throws — always check `result.success`:
87
+
88
+ ```js
89
+ const result = await logger.log({ message: "Payment failed", level: "ERROR" });
90
+
91
+ if (!result.success) {
92
+ console.error(result.error);
93
+ } else {
94
+ console.log(`Log saved. Total count: ${result.data.count}`);
95
+ }
96
+ ```
97
+
98
+ ---
99
+
100
+ ## Log levels
101
+
102
+ | Level | When to use |
103
+ | ----- | ----------------------------------- |
104
+ | INFO | General info, lifecycle events |
105
+ | WARN | Minor issues, degraded behavior |
106
+ | ERROR | Critical bugs, failures, exceptions |
package/index.cjs ADDED
@@ -0,0 +1,3 @@
1
+ 'use strict';
2
+
3
+ module.exports = require('./src/core.js');
package/index.mjs ADDED
@@ -0,0 +1,5 @@
1
+ import core from './src/core.js';
2
+
3
+ export const init = core.init;
4
+ export const log = core.log;
5
+ export default core;
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "astro-logger-sdk",
3
+ "version": "1.0.0",
4
+ "description": "SDK for sending logs to AppLogger platform.",
5
+ "main": "index.cjs",
6
+ "module": "index.mjs",
7
+ "exports": {
8
+ ".": {
9
+ "require": "./index.cjs",
10
+ "import": "./index.mjs"
11
+ }
12
+ },
13
+ "files": [
14
+ "index.cjs",
15
+ "index.mjs",
16
+ "src/",
17
+ "README.md"
18
+ ],
19
+ "keywords": [
20
+ "logging",
21
+ "sdk",
22
+ "applogger"
23
+ ],
24
+ "license": "MIT"
25
+ }
package/src/core.js ADDED
@@ -0,0 +1,147 @@
1
+ 'use strict';
2
+
3
+ const VALID_LEVELS = ['INFO', 'WARN', 'ERROR'];
4
+
5
+ let _apiKey = null;
6
+ let _appName = null;
7
+ let _baseUrl = null;
8
+
9
+ /**
10
+ * Initialize the logger SDK.
11
+ * Must be called once before using log().
12
+ *
13
+ * @param {object} options
14
+ * @param {string} options.apiKey - Your developer API key
15
+ * @param {string} options.appName - Your application name (no whitespace)
16
+ * @param {string} options.baseUrl - Base URL of your logging server (e.g. 'https://api.mylogger.com')
17
+ */
18
+ function init({ apiKey, appName, baseUrl }) {
19
+ if (!apiKey || typeof apiKey !== 'string') {
20
+ throw new Error('[logger-sdk] init() requires a valid "apiKey" string.');
21
+ }
22
+ if (!appName || typeof appName !== 'string') {
23
+ throw new Error('[logger-sdk] init() requires a valid "appName" string.');
24
+ }
25
+ if (!baseUrl || typeof baseUrl !== 'string') {
26
+ throw new Error('[logger-sdk] init() requires a valid "baseUrl" string.');
27
+ }
28
+
29
+ _apiKey = apiKey.trim();
30
+ _appName = appName.trim();
31
+ _baseUrl = baseUrl.replace(/\/$/, ''); // strip trailing slash
32
+ }
33
+
34
+ /**
35
+ * Send a log entry to the server.
36
+ *
37
+ * @param {object} options
38
+ * @param {string} options.message - Log message
39
+ * @param {'INFO'|'WARN'|'ERROR'} options.level - Log level
40
+ * @returns {Promise<{ success: boolean, data?: object, error?: string, status?: number }>}
41
+ */
42
+ async function log({ message, level }) {
43
+ // ── Local validation ────────────────────────────────────────────────────────
44
+
45
+ if (!_apiKey || !_appName || !_baseUrl) {
46
+ return {
47
+ success: false,
48
+ error: '[logger-sdk] SDK not initialized. Call init() before log().',
49
+ };
50
+ }
51
+
52
+ if (!message || typeof message !== 'string' || message.trim() === '') {
53
+ return {
54
+ success: false,
55
+ error: '[logger-sdk] "message" is required and must be a non-empty string.',
56
+ };
57
+ }
58
+
59
+ if (!level) {
60
+ return {
61
+ success: false,
62
+ error: '[logger-sdk] "level" is required. Use "INFO", "WARN", or "ERROR".',
63
+ };
64
+ }
65
+
66
+ if (!VALID_LEVELS.includes(level)) {
67
+ return {
68
+ success: false,
69
+ error: `[logger-sdk] Invalid level "${level}". Use "INFO", "WARN", or "ERROR".`,
70
+ };
71
+ }
72
+
73
+ // ── HTTP request ─────────────────────────────────────────────────────────────
74
+
75
+ const url = `${_baseUrl}/api/applications/${_appName}/logs`;
76
+
77
+ let response;
78
+ let body;
79
+
80
+ try {
81
+ response = await fetch(url, {
82
+ method: 'POST',
83
+ headers: {
84
+ 'Content-Type': 'application/json',
85
+ 'x-api-key': _apiKey,
86
+ },
87
+ body: JSON.stringify({ message: message.trim(), level }),
88
+ });
89
+
90
+ body = await response.json();
91
+ } catch (networkError) {
92
+ // Network failure — server unreachable, DNS error, timeout, etc.
93
+ return {
94
+ success: false,
95
+ error: `[logger-sdk] Network error: ${networkError.message}. Check your baseUrl and internet connection.`,
96
+ };
97
+ }
98
+
99
+ // ── Response handling ────────────────────────────────────────────────────────
100
+
101
+ if (response.status === 201 && body.success) {
102
+ return {
103
+ success: true,
104
+ data: body.data,
105
+ };
106
+ }
107
+
108
+ // Map every documented error scenario to a clear message
109
+ switch (response.status) {
110
+ case 400:
111
+ return {
112
+ success: false,
113
+ status: 400,
114
+ error: `[logger-sdk] Validation error: ${body.message}`,
115
+ };
116
+
117
+ case 401:
118
+ return {
119
+ success: false,
120
+ status: 401,
121
+ error: '[logger-sdk] Unauthorized: API key was not provided or is missing. Check your apiKey in init().',
122
+ };
123
+
124
+ case 403:
125
+ return {
126
+ success: false,
127
+ status: 403,
128
+ error: '[logger-sdk] Forbidden: The API key does not belong to this application. Make sure apiKey and appName match.',
129
+ };
130
+
131
+ case 404:
132
+ return {
133
+ success: false,
134
+ status: 404,
135
+ error: `[logger-sdk] Application not found: No application named "${_appName}" exists on the server.`,
136
+ };
137
+
138
+ default:
139
+ return {
140
+ success: false,
141
+ status: response.status,
142
+ error: `[logger-sdk] Unexpected server error (${response.status}): ${body.message || 'No message provided.'}`,
143
+ };
144
+ }
145
+ }
146
+
147
+ module.exports = { init, log };