Files
MyDIAPp/src/logger/appenders/Appender.ts
Alexander Zinn ce85dd1ead Enhance API routing and health check functionality
- Added ApiRouteTemplate as a base class for defining API routes
- Implemented HealthCheckApi for health check endpoint management
- Introduced IApiRoute interface for consistent route handling
- Updated UserApiRoute to align with new routing structure
- Added HealthCheck class for health status retrieval
- Improved dependency management with new types and interfaces
2025-11-10 22:12:41 -05:00

64 lines
1.9 KiB
TypeScript

import {type LoggingLevelType} from '../LoggingLevel';
import type ILogMessage from './LogMessage';
export type AppenderOptions = {
domain?: string;
};
export default class Appender {
private readonly _logRecorderUrl: string = 'https://logserver.techniker.me/api/logs';
// @ts-expect-error browser vs node
private readonly _domain: string = typeof globalThis !== 'undefined' ? (globalThis.location?.hostname ?? '') : '';
private readonly _logMessageQueue: ILogMessage[] = [];
private _pendingPostLogMessagePromise: Promise<Response | undefined> | undefined = undefined;
constructor(logRecorderUrl: string, {domain}: AppenderOptions) {
this._logRecorderUrl = logRecorderUrl;
this._domain = domain ?? this._domain;
}
public log(timestamp: string, level: LoggingLevelType, category: string, message: string): void {
const logMessage = {
timestamp,
domain: this._domain,
level,
category,
message
};
this.queueMessage(logMessage);
this.postLogMessage();
}
private async postLogMessage(): Promise<void> {
const logMessage = this._logMessageQueue.shift();
if (!logMessage || this._pendingPostLogMessagePromise !== undefined) {
return;
}
try {
if (typeof fetch === 'undefined') {
console.error('Fetch API is not available in this environment');
return;
}
this._pendingPostLogMessagePromise = fetch(this._logRecorderUrl, {
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
mode: 'no-cors',
method: 'POST',
body: JSON.stringify(logMessage)
}).then(() => (this._pendingPostLogMessagePromise = undefined));
} catch (e) {
console.error('Unable to send logs due to [%o]', e);
return;
}
}
private queueMessage(logMessage: ILogMessage): void {
this._logMessageQueue.push(logMessage);
}
}