Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MvvmCross Mvx.Trace usage

I'm using MvvmCross. In the library I see usage of Mvx.Trace method, but no output to the console/output window. How to use it?

p.s. I have set the compiler constant Trace = true

Thanks.

like image 890
Arthur Kater Avatar asked Jun 21 '13 11:06

Arthur Kater


2 Answers

MvvmCross DebugTrace is all routed via a singleton implementation of IMvxTrace

Each platform provides different implementations of this:

  • the Windows platforms use Debug trace (because Trace itself is not available on all the Windows platforms)
  • Android uses a dual log of both Debug and the Android log
  • iOS uses a dual log of both Debug and the iOS Console

This worked well in earlier versions of MvvmCross, especially where people linked directly to the MvvmCross source code and so could bind directly to either the debug or release MvvmCross binaries.

However... because people are now increasingly using the release Binaries from Nuget - in which Debug is of course compiled out, then this often leaves people asking "How to use it?"

The easiest way is for you to override the initialisation of IMvxTrace in your Setup class.

This is easy to do - e.g.:

   protected override IMvxTrace CreateDebugTrace() { return new MyDebugTrace(); }

where MyDebugTrace is something like:

public class MyDebugTrace : IMvxTrace
{
    public void Trace(MvxTraceLevel level, string tag, Func<string> message)
    {
        Debug.WriteLine(tag + ":" + level + ":" + message());
    }

    public void Trace(MvxTraceLevel level, string tag, string message)
    {
        Debug.WriteLine(tag + ":" + level + ":" + message);
    }

    public void Trace(MvxTraceLevel level, string tag, string message, params object[] args)
    {
        try
        {
            Debug.WriteLine(string.Format(tag + ":" + level + ":" + message, args));
        }
        catch (FormatException)
        {
            Trace(MvxTraceLevel.Error, tag, "Exception during trace of {0} {1} {2}", level, message);
        }
    }
}

If you wanted to include different implementations for debug/release; if you wanted to switch this on/off at runtime; if you wanted to filter on MvxTraceLevel or tag; or if you wanted to use some third party logging engine then this should also be easy to do using simple C# on each platform.

like image 145
Stuart Avatar answered Nov 03 '22 04:11

Stuart


Just hitting an issue on iOS with the current solution provided by Stuart.

Running a debug session in VS with the MvxTrace using Debug.WriteLine can be extremely slow depending on how verbose is your app logging. Same for Trace.WriteLinte. Use Console.WriteLine instead (as MvvmCross MvxDebugTrace does) which is not impacted.

See this Xamarin bug item for "more" details: https://bugzilla.xamarin.com/show_bug.cgi?id=13538#c4

like image 37
GGirard Avatar answered Nov 03 '22 04:11

GGirard