Skip to content

Commit

Permalink
Add default fields for wshim logs
Browse files Browse the repository at this point in the history
Add tags and fields that will be sent to the a logger.
  • Loading branch information
thibmeu committed Dec 4, 2024
1 parent 0a70961 commit 8fc780f
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 10 deletions.
28 changes: 22 additions & 6 deletions src/context/logging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,18 +167,23 @@ export class VoidLogger implements Logger {

interface LogEntry {
message: string;
level: string;
log_level: string;
error?: string;
}

export class WshimLogger {
private request: Request;
private env: Bindings;

private logs: LogEntry[] = [];
private serviceToken: string;
private sampleRate: number;
private fetcher: typeof fetch;
private loggingEndpoint: string;

constructor(env: Bindings, sampleRate: number = 1) {
constructor(request: Request, env: Bindings, sampleRate: number = 1) {
this.request = request;
this.env = env;
if (typeof sampleRate !== 'number' || isNaN(sampleRate) || sampleRate < 0 || sampleRate > 1) {
throw new Error('Sample rate must be a number between 0 and 1');
}
Expand All @@ -193,11 +198,20 @@ export class WshimLogger {
return Math.random() < this.sampleRate;
}

private defaultFields() {
return {
'environment': this.env.ENVIRONMENT,
'http.host': this.request.url,
'http.user_agent': this.request.headers.get('User-Agent'),
'source_service': this.env.SERVICE,
};
}

log(...msg: unknown[]): void {
if (!this.shouldLog()) return;

const message = msg.map(o => (typeof o === 'object' ? JSON.stringify(o) : String(o))).join(' ');
const logEntry: LogEntry = { message, level: 'info' };
const logEntry: LogEntry = { message, log_level: 'info' };
this.logs.push(logEntry);
}

Expand All @@ -210,14 +224,14 @@ export class WshimLogger {
const error = msg[0] as Error;
logEntry = {
message: error.message,
level: 'error',
log_level: 'error',
error: error.stack,
};
} else {
const message = msg
.map(o => (typeof o === 'object' ? JSON.stringify(o) : String(o)))
.join(' ');
logEntry = { message, level: 'error' };
logEntry = { message, log_level: 'error' };
}

this.logs.push(logEntry);
Expand All @@ -226,8 +240,10 @@ export class WshimLogger {
public async flushLogs(): Promise<void> {
if (this.logs.length === 0) return;

const defaultFields = this.defaultFields();

const body = JSON.stringify({
logs: this.logs,
logs: this.logs.map(log => ({ message: { ...defaultFields, ...log } })),
});

try {
Expand Down
5 changes: 3 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,13 +320,14 @@ export default {
},

async scheduled(event: ScheduledEvent, env: Bindings, ectx: ExecutionContext) {
const sampleRequest = new Request(`https://schedule.example.com`);
const ctx = new Context(
new Request(`https://schedule.example.com`),
sampleRequest,
env,
ectx.waitUntil.bind(ectx),
new ConsoleLogger(),
new MetricsRegistry(env),
new WshimLogger(env)
new WshimLogger(sampleRequest, env)
);
const date = new Date(event.scheduledTime);

Expand Down
2 changes: 1 addition & 1 deletion src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ export class Router {
private buildContext(request: Request, env: Bindings, ectx: ExecutionContext): Context {
// Prometheus Registry should be unique per request
const metrics = new MetricsRegistry(env);
const wshimLogger = new WshimLogger(env);
const wshimLogger = new WshimLogger(request, env);

// Use a flexible reporter, so that it uses console.log when debugging, and Core Sentry when in production
let logger: Logger;
Expand Down
2 changes: 1 addition & 1 deletion test/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export interface MockContextOptions {
export const getContext = (options: MockContextOptions): Context => {
const logger = options.logger ?? new ConsoleLogger();
const metrics = options.metrics ?? new MetricsRegistry(options.env);
const wshimLogger = options.wshimLogger ?? new WshimLogger(options.env);
const wshimLogger = options.wshimLogger ?? new WshimLogger(options.request, options.env);
const waitUntilFunc = options.waitUntilFunc || options.ectx.waitUntil.bind(options.ectx);
return new Context(options.request, options.env, waitUntilFunc, logger, metrics, wshimLogger);
};
Expand Down

0 comments on commit 8fc780f

Please sign in to comment.