Is there a way to add a virtual method behaviour for every controller method? (i.e logging)

Viewed 54

After my research, my own answer to my question is: unfortunately, no. But I'd like to hear your opinion as well.

I have 4 controllers each having 5 methods. Every method has a try-catch block. In case of an exception, I want to log on a file a message with all the parameters of that controllers. So I have to write the basically same log instruction 4x5=20 times. If I want to change the logging message, I have to do it 20 times. On one hand, sounds like a hard to maintain problem. But on the other hand, every controller has its own signature.

Would it be possible to have some base/parent/God method that virtually logs for every controller? And of course if I will be needing to adapt/override the logging instruction just for one controller this should be also possible. Is there any technique?

How about if I just need to generate for every controller methods a GUID?

1 Answers

There are many ways to achieve a single piece of code that can log all your controller methods. The easiest implementation which comes to my mind is to just write a method that takes an action or function. Then inside just call that action/function and wrap it in any logging that you wish to use. Like so:

public void ExecuteWithLogging(Action actionToExecute)
{
    try
    {
        action() // the same as action.Invoke()
    }
    catch(Exception e)
    {
        // code your logging here
    }
}

then inside your controller's methods you could use it like this:

ExecuteWithLogging(() =>
{
    // your controller code
});

But there are other ways. You could probably use attributes to mark each method as logged. Or maybe you could write some middle-ware that just logs everything (like maybe in this article -> https://exceptionnotfound.net/using-middleware-to-log-requests-and-responses-in-asp-net-core/).

The options are many!

Related