I've implemented a specific implementation of IMvxTrace that logs to a file as well as the console, and it's working just fine. But what I'd like to do now is add a new method that I can use to log Exceptions, so I'd like to add a method signature to the interface.
I was thinking about doing something like this:
public interface IMvxTraceExt : IMvxTrace
{
void LogException(Exception ex);
}
And just creating an object that implements that, but of course when I finally make the object and return it in CreateDebugTrace
, it looses the extended interface definition:
protected override IMvxTrace CreateDebugTrace()
{
return new DebugTrace();
}
It's not really surprising... Overall the objective would be to have it so that I could do the following in code:
MvxTrace.TaggedError("Setup", "registering unhandled exception logging");
AppDomain.CurrentDomain.UnhandledException += (sender, e) => {
var trace = MvxTrace.Instance as IMvxTraceExt;
trace.LogException(e.ExceptionObject as Exception);
};
Above, 'trace' becomes null with the cast -- so the cast isn't doing what I was thinking it might. Really, my preference would be able to just hit the method directly off of MvxTrace like so:
MvxTrace.TaggedError("Setup", "registering unhandled exception logging");
AppDomain.CurrentDomain.UnhandledException += (sender, e) => {
MvxTrace.LogException(e.ExceptionObject as Exception);
};
But that implies that MvxTrace itself needs to be a type that implements the extended mvxtrace interface, and I don't see a way of doing that other than to tweak the source itself which I'm not really wanting to do.
Side note: The reason I want LogException in the same object that implements the other trace functions is because I've got code that manages appending to a log file in there and it seems natural to extend it in this way.
Thoughts?
MvxTrace
itself is just a set of static helper methods to make calls to the actual IMvxTrace
implementation less verbose and as an optimisation - MvxTrace
acts as a singleton in order to avoid looking up IMvxTrace
as a Service for every single trace call.
Because the helpers are static
then it's not going to be easy to override that class and change the behaviour.
For your requirements, you could declare an additional TraceEx
static class to help:
public class MyTrace
{
private static IMvxTraceExt _traceExt;
private static IMvxTraceExt TraceExt
{
get { return _traceExt ?? _traceExt = Mvx.Resolve<IMvxTrace>() as IMvxTraceExt; }
}
public static void LogException(Exception exc)
{
TraceExt.LogException(exc):
}
}
This may seem like a hassle... but it only has to be done once - and I often add an application specific static trace class anyway - as it helps ensure consistency of trace Tag
logging - e.g. see https://github.com/MvvmCross/MvvmCross-Tutorials/blob/master/Sample%20-%20CirriousConference/Cirrious.Conference.Core/Trace.cs