I am currently in deep need of logging for an existing application, and can’t afford to add the level of logging I expect directly into the code. As a workaround, I’d be happy to have a certain amount of logging done each time an event is fired.
I am considering a solution where I could, at runtime, parse the whole application to wrap all event-to-handler bindings with event-to-wrapper-to-handler; and, ideally, unwrap them at runtime too. In Pseudo-code, this would be:
IDictionary<Event, Action<object, EventArgs>) originalBindings = ...;
public void SetWrapBindings()
{
var allBindingsToReplace = Assembly.GetAssembly().GETALLEVENTS()
.Where(eventInfo => eventInfo.GetOtherMethods().Any());
foreach(var binding in allBindingsToReplace)
{
binding.event -= binding.handler;
binding.event += HandlerWrapper;
originalBindings.Add(binding.event, binding.handler);
}
}
public static void HandlerWrapper(object o, EventArgs e)
{
// Do some logging
try
{
var handler = originalBindings.TryGetValue(/* something */);
handler.Invoke(o, e);
}
// Do more logging
}
In this bunch of pseudo-code there are lots of steps I was not able to write, possibly because I didn’t find the correct API use, but maybe also because some operation in that is theoretically impossible (in which case I’d love to know why). These are:
- Iterating over all events of the application (this would probably be easy)
- Identifying a good key for my IDictionary
- At each step, get the relevant information from the context
Of course, binding one extra handler to each existing event (pre/post-executing a routine without really wrapping the handler) would help, but executing the real handler inside a try-catch is a big nice to have.
Any partial answer is still greatly appreciated
If you’re looking for non-invasive system-wide logging, you’d be better off using an aspect-oriented programming framework like PostSharp. This page provides a decent jumping off point for what you’re looking for.
Edit: To add to this, look at implementing an
EventInterceptionAspectif you really do just want to know when any event is raised. Again, the PostSharp blog is a good source of info, and this article shows an implementation of this aspect that does simple stdout logging of adding, removing, and invoking.