Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make it easier to get the global logger #633

Merged
merged 1 commit into from
Sep 30, 2024
Merged

Conversation

chuck-dbos
Copy link
Collaborator

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)

@chuck-dbos chuck-dbos merged commit f0af95c into main Sep 30, 2024
14 checks passed
@chuck-dbos chuck-dbos deleted the chuck/globallogger branch September 30, 2024 19:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants