I'm frequently frustrated by the amount of logging I have to include in my code and it leads me to wonder if there's a better way of doing things.
I don't know if this has been done or if someone has come up with a better idea but I was wondering is there a way anyone knows of to "inject" a logger into an application such that it passively monitors the thread and quietly logs processes as they occur without having to do things like:
public void MyProcess(int a, string b, object c)
{
log(
String.Format(
"Entering process MyProcess with arguments: [a] = [{0}]; [b] = [{1}]; [c] = [{2}]",
a.ToString(),
b,
c.ToString()
);
try
{
int d = DoStuff(a)
log(
String.Format(
"DoStuff({0}) returned value {1}",
a.ToString(),
d.ToString()
)
);
}
catch (Exception ex)
{
log(
String.Format("An exception occurred during process DoStuff({0})\nException:\n{1}",
a.ToString(),
ex.ToString())
)
}
}
What would be great is if I could say to my logger:
Monitor(MyClass.MyMethod)
It would then monitor everything that goes on inside of that method including passed in arguments along with method calls and values passed into those methods, exceptions that occur etc.
Has anyone implemented something like this in the past? Could it even be implemented? Is logging in this fashion just a pipe dream?
I'd love to design something that would do this, but I just don't even know where I'd begin. Of course, I don't want to reinvent the wheel either, if it's already been done, it would be great if someone could point me in the right direction.
Any suggestions would be gratefully received...
Edit: I thought I'd comment on an answer which queried as to the level of detail required in the log. It is frequently required that configurable levels of logging be provided such that if the configuration specifies detailed logging then everything is logged, whereas if critical logging is configured then only certain information is logged along with exceptions. If fatal logging is configured then only information which causes the application to die would be logged. Would something like this be configurable or would AOP require 3 or 4 different builds depending on the number of logging levels?
I frequently use 4 levels: Fatal, Critical, Information, Detailed