如何在MvvmCross中使用IMvxTrace

时间:2018-09-17 19:32:48

标签: c# xamarin logging mvvmcross

最近我开始研究Xamarin,今天我打开了一个用MvvmCross编写的大型项目,我必须在此添加新功能。就像我通常使用Java和Android Studio一样,这很困难,但是现在我必须深入研究C#和Visual Studio。

首先,我想了解这个项目的流程,为此,我想在不同的.cs类中插入日志,并在浏览应用程序时查看它们。

在Setup.cs中:

create

NLogTrace.cs:

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

因此,我看到了一些记录器,但是我不知道如何在某些.cs文件中使用它。 能否提供一些代码段

public class NLogTrace : IMvxTrace
{
    private readonly ILogger _logger;

    public NLogTrace()
    {
        InitializeNLog();

        _logger = LogManager.GetLogger("MvvmCross");
    }

    public static string LogFileName => Path.Combine(GetCacheFolder(), "logFile.txt");

    private static void InitializeNLog()
    {
        // Step 1. Create configuration object 
        var config = new LoggingConfiguration();

        // Step 2. Create targets and add them to the configuration 
        var consoleTarget = new ConsoleTarget();
        config.AddTarget("console", consoleTarget);

        var logFolderPath = GetCacheFolder();
        var fileTarget = new FileTarget
        {
            FileName = Path.Combine(logFolderPath, "logFile.txt"),
            ArchiveFileName = Path.Combine(logFolderPath, "log.{#}.txt"),
            ArchiveEvery = FileArchivePeriod.Day,
            ArchiveNumbering = ArchiveNumberingMode.Date,
            MaxArchiveFiles = 7
        };
        config.AddTarget("file", fileTarget);

        // Step 3. Set target properties 
        consoleTarget.Layout = @"${longdate}|${level:uppercase=true}|${logger}|${message}"; //
        fileTarget.Layout = "${longdate}|${level:uppercase=true}|${logger}|${message}";

        // Step 4. Define rules
        var rule1 = new LoggingRule("*", LogLevel.Trace, consoleTarget);
        config.LoggingRules.Add(rule1);

        #if DEBUG
        var rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget);
        config.LoggingRules.Add(rule2);
        #else
        var rule2 = new LoggingRule("*", LogLevel.Info, fileTarget);
        config.LoggingRules.Add(rule2);
        #endif

        LogManager.Configuration = config;
    }

    private static string GetCacheFolder()
    {
        var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        var relativeCacheFolderPath = Path.Combine(documents, "Storage", "Logs");

        var directory = new DirectoryInfo(relativeCacheFolderPath);
        var resolvedCacheFolderPath = directory.FullName;
        return resolvedCacheFolderPath;
    }

    public void Trace(MvxTraceLevel level, string tag, string message)
    {
        switch (level)
        {
            case MvxTraceLevel.Diagnostic:
                _logger.Debug(message);
                break;
            case MvxTraceLevel.Warning:
                _logger.Warn(message);
                break;
            case MvxTraceLevel.Error:
                _logger.Error(message);
                break;
        }
    }

    public void Trace(MvxTraceLevel level, string tag, Func<string> message)
    {
        switch (level)
        {
            case MvxTraceLevel.Diagnostic:
                _logger.Debug(message());
                break;
            case MvxTraceLevel.Warning:
                _logger.Warn(message());
                break;
            case MvxTraceLevel.Error:
                _logger.Error(message());
                break;
        }
    }

    public void Trace(MvxTraceLevel level, string tag, string message, params object[] args)
    {
        switch (level)
        {
            case MvxTraceLevel.Diagnostic:
                _logger.Debug(message, args);
                break;
            case MvxTraceLevel.Warning:
                _logger.Warn(message, args);
                break;
            case MvxTraceLevel.Error:
                _logger.Error(message, args);
                break;
        }
    }
}

从.Core或.Droid项目中任意选择的.cs文件中?

2 个答案:

答案 0 :(得分:1)

您必须利用依赖注入。有关完整的文档see docs。简而言之,您可以在视图模型/服务构造函数中添加一个IMvxLog参数:

public MyViewModel( IMvxLog logger )
{
   this._logger = logger;
}

然后在_logger上调用适当的方法:

_log.Trace("Some message");

如果要在无法设置依赖项注入的类中使用IMvxLog,可以使用Mvx来解决它:

var logger = Mvx.Resolve<IMvxLog>();

答案 1 :(得分:0)

我找到了答案。 首先,上面的代码是没有用的。

对于android项目中的文件,我可以使用简单的android日志:

using Android.Util;
.......
Log.Info("TAG", "Sending confirmation that app is running");

对于.Core项目中的文件(也适用于android文件),我在下一个代码链中找到了

interface ILogger

用于

interface ILogService

在.Droid中实现为

 AndroidLogService : ILogService

,并在Setup.cs中注册为

Mvx.LazyConstructAndRegisterSingleton<ILogService, AndroidLogService>();

用于.Droid项目中的文件:

private readonly ILogger _logger;

public AndroidSomeService(ILogService logService)
{
    _logger = logService.GetLogger<AndroidSomeService>();
    .......
}

_logger.Warn("Failed to retrieve logo. Error: {0}", ex);