@intheroomglobal/cf-worker-logger
v0.5.0
Published
Configurable Cloudflare Worker logger that allows sending logs to destination of choice
Downloads
8
Readme
Cloudflare Worker Logger
A re-usable logger for use in Cloudflare Workers. Extend the class to add custom event transforms and transports. Allows logs to be sent to any destination. In worker environments waitUntil
is called automatically when logging.
Installation
npm i -S @intheroomglobal/cf-worker-logger
Usage
Extend the logger to transform events as you require and to send to your logging endpoint:
import Logger, { type LogEvent } from '@intheroomglobal/cf-worker-logger';
type Env = {
LOGS_URL: 'http://my.logging.service',
LOGS_TOKEN: 'myapitoken'
}
export class MyLogger extends Logger<Env> {
transformEvent(event: LogEvent) {
return {
...event,
my: {
custom: 'fields'
}
};
}
send(event: LogEvent) {
return fetch(this.env.LOGS_URL, {
method: 'POST',
headers: {
'authorization': `Bearer ${this.env.LOGS_TOKEN}`
},
body: JSON.stringify(event)
});
}
}
- Log requests and responses:
export default {
async fetch(request, env, context) {
const logger = new MyLogger(request, env, context);
const start = Date.now();
const response = new Response('Hello, World!', { status: 200 });
logger.logResponse(response, Date.now() - start);
return response;
}
}
- Attach a logger to requests:
import Logger from '@foreverholdings/logflare-logging';
export default {
async fetch(request, env, context) {
request.logger = new Logger(request, env, context);
return handleRequest(request);
}
}
function handleRequest(request) {
request.logger.info('Returning a greeting');
return Response('Hello, World!', { status: 200 });
}