dbos-inc / dbos-transact-ts

The TypeScript framework for backends that scale
https://docs.dbos.dev
MIT License
374 stars 28 forks source link

Make it easier to get the global logger #633

Closed chuck-dbos closed 2 months ago

chuck-dbos commented 2 months ago

Export a global logger, so that your middleware can do something like this:

// Logging middleware
const logAllRequests = () => {
    return async (ctx: Koa.Context, next: Koa.Next) => {
        const start = Date.now();

        // Log the request method and URL
        DBOS.globalLogger?.info(`[Request] ${ctx.method} ${ctx.url}`);

        let ok = false;
        try {
            await next();
            ok = true;
        }
        finally {
            const ms = Date.now() - start;
            if (ok) {
                // Log the response status and time taken
                DBOS.globalLogger?.info(`[Response] ${ctx.method} ${ctx.url} - ${ctx.status} - ${ms}ms`);
            }
            else {
                // Log error response
                DBOS.globalLogger?.warn(`[Exception] ${ctx.method} ${ctx.url} - ${ctx.status} - ${ms}ms`);
            }
        }

    };
};

@KoaGlobalMiddleware(logAllRequests)