I have a class Logger with a number of static methods for various user activity logging. Something like:
public static class Logger
{
public static void FileDownload(int fileId, int userId)
{
// Do stuff
}
// ... and a number of similar additional methods
}
So what I’ve come to now is that I want to ignore logging the activity for users of a certain role.
The idea I had, to avoid rewriting a lot of code and for the purpose of DRY, was to implement a custom attribute that I can use on the Logger class, which will, for every method call, verify if the user is in a certain role, and in that case I want to ignore the method call altogether.
The problem I can’t wrap my head around is how to intercept and abort the method-call within my attribute.
Is it possible, or is there some other more efficient way to intercept a method call and ignore it if a certain condition is true?
A way to do this efficiently and
DRYis to change those methods fromstaticto instance methods, then inherit from classLoggerand override its methods to do nothing.Your
Loggerclass will now look like this:And the subclass will look like this:
Then you can say:
…and you are done! Simple, efficient, DRY and elegant.