5

I'm trying to implement some logging around my web api calls. Nothing too fancy, but I'm still learning async/await and would like the logging to happen without disrupting performance.

Here's an example of what I'd like to implement, just not totally sure how to do it.

public class Logging : ActionFilterAttribute
{
    public override async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
    {
        // DoLoggingHere();   ????
        base.OnActionExecutingAsync(actionContext, cancellationToken);
        // OrDoLoggingHere();  ????

        // Also, what does the return look like if any?
    }

    public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
    {
        // This method should/could complete before the logging completes.
        base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);

        // Might log here too.
    }
}

Basically I don't want any of my logging to get in the way of the HTTP call. It should be transparent.

Looking for any help!

1

1 Answer 1

2

You can await the call, so that thread is returned to pool for more incoming requests and then do logging after the call completes:

var result = await base.OnActionExecutingAsync(actionContext, cancellationToken);
// logging code here

return result;
Sign up to request clarification or add additional context in comments.

5 Comments

Could base.OnActionExecutedAsync() be called before my logging finishes?
your logging will be done after OnActionExecuting returns some result back, as we are awaiting it, and yes it will complete before OnActionExecuted gets called
I'm asking for the opposite. I would like to see OnActionExecuted be called first, then my logging.
then you have to await base.OnActionExecuted and after that logging code to be executed
await base.OnActionExecutingAsync(actionContext, cancellationToken); returns a void, cannot get the result like this var result = ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.