Skip to content

Commit

Permalink
feat: integrate logs package
Browse files Browse the repository at this point in the history
  • Loading branch information
ktranish committed Nov 17, 2024
1 parent abe0491 commit c9f9e9d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 8 deletions.
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,8 @@
"jest": "^29.7.0",
"ts-jest": "^29.2.5",
"typescript": "^5.6.3"
},
"dependencies": {
"@ktranish/logs": "^1.1.5"
}
}
32 changes: 24 additions & 8 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { Logs } from "@ktranish/logs"; // Logs package for Elasticsearch logging

/**
* Logger Types and Configuration
*/
export type HookLogger = {
onRequest?: (url: string, options: RequestInit) => void | Promise<void>;
onResponse?: (url: string, response: Response) => void | Promise<void>;
onError?: (url: string, error: Error) => void | Promise<void>;
logs?: Logs; // Optional Logs instance for Elasticsearch
};

let globalLogger: Readonly<HookLogger> = {};
Expand Down Expand Up @@ -144,23 +147,36 @@ async function coreHook<T = any>(
const endTime = performance.now();
const responseTime = endTime - startTime;

if (!response.ok) {
// Single point for failed analytics update
updateAnalytics(method, response.status, responseTime);
throw new Error(
`[Hook] Request failed with status ${response.status}: ${response.statusText}`
);
}

// Analytics for successful responses
updateAnalytics(method, response.status, responseTime);

// Log to Elasticsearch if enabled
if (localLogger.logs) {
await localLogger.logs.log("info", "HTTP Request", {
method,
url,
status: response.status,
responseTime,
timestamp: new Date().toISOString(),
});
}

await localLogger.onResponse?.(url, response);
return await parseResponse<T>(response);
} catch (error: any) {
// Log the error but do not update analytics
await localLogger.onError?.(url, error);

// Log the error to Elasticsearch if enabled
if (localLogger.logs) {
await localLogger.logs.log("error", "HTTP Error", {
method,
url,
error: error.message,
timestamp: new Date().toISOString(),
});
}

throw error; // Re-throw for external handling
}
}
Expand Down

0 comments on commit c9f9e9d

Please sign in to comment.