跨平台登录Xamarin

use*_*360 22 xamarin.ios xamarin.android ios xamarin

我正在寻找一个日志实用程序,如NLog,Log4Net等...这将允许我登录我的Xamarin.Andriod,Xamarin.IOS和Xamarin.PCL项目.到目前为止我看过的所有记录器由于各种原因(大多数文件IO)都不支持PCL项目.是否有任何解决方案可用于支持跨平台方式的日志记录,包括PCL项目?如果没有,你是如何在PCL(设计模式等)中实现日志记录的?

谢谢

SKa*_*all 5

如果没有PCL记录器,您可能希望使用依赖注入.以下只是一个概念(虽然它确实有效),有两个示例实现(Android Log和SQLite数据库).

接近Android的Log类的抽象接口:https: //github.com/sami1971/SimplyMobile/blob/master/Core/SimplyMobile.Core/Logging/ILogService.cs

Android特定实现,一个围绕Log类的包装:https: //github.com/sami1971/SimplyMobile/blob/master/Android/SimplyMobile.Android/Logging/LogService.cs

与CRUD提供程序相关的数据库日志记录的PCL实现:https: //github.com/sami1971/SimplyMobile/blob/master/Core/SimplyMobile.Core/Data/DatabaseLog.cs

SQLite.Net.Async PCL兼容库(适用于iOS,Android和WP8)的CRUD提供程序包装器:https: //github.com/sami1971/SimplyMobile/blob/master/Core/Plugins/Data/SimplyMobile.Data.SQLiteAsync/ SQLiteAsync.cs

ServiceStack.OrmLite的CRUD提供程序包装器(适用于iOS和Android):https: //github.com/sami1971/SimplyMobile/blob/master/Core/Plugins/SimplyMobile.Data.OrmLite/OrmLite.cs

在应用程序级别,使用IoC容器注册要使用的服务.示例适用于WP8,但要将其用于iOS和Android,您只需要更改ISQLitePlatform.

  DependencyResolver.Current.RegisterService<ISQLitePlatform, SQLitePlatformWP8>()
       .RegisterService<IJsonSerializer, SimplyMobile.Text.ServiceStack.JsonSerializer>()
       .RegisterService<IBlobSerializer>(t => t.GetService<IJsonSerializer>().AsBlobSerializer())
       .RegisterService<ILogService>(t =>
                new DatabaseLog(
                    new SQLiteAsync(
                        t.GetService<ISQLitePlatform>(), 
                        new SQLiteConnectionString(
                            Path.Combine(ApplicationData.Current.LocalFolder.Path, "device.log"),
                            true,
                            t.GetService<IBlobSerializer>())
                    )));
Run Code Online (Sandbox Code Playgroud)

使用Android Log-wrapper当然会简单得多,因为它没有任何依赖:

DependencyResolver.Current.RegisterService<ILogService, LogService>();
Run Code Online (Sandbox Code Playgroud)


小智 4

根本没有跨平台的解决方案。您可以通过使用服务来解决它。因此,创建接口 ILogging 并描述日志记录所需的所有方法。然后实现Logging,它在每个平台上实现ILogging。之后在每个平台上设置注册它

     Mvx.RegisterSingleton<ILogging >(new Logging());
Run Code Online (Sandbox Code Playgroud)

之后您可以从核心项目轻松访问它

    Mvx.Resolve<ILogging>();
Run Code Online (Sandbox Code Playgroud)

  • Serilog 是一个不错的选择(https://github.com/serilog/serilog)。它具有 Xamarin 扩展(https://github.com/serilog/serilog-sinks-xamarin),或者您可以获取两个类(对于 ios 为:LoggerConfigurationMonoTouchExtensions.cs 和 NSLogSink.cs)并将它们包含在您的应用程序中。创建不同的接收器非常容易,并且有很多已经开发和开源。 (2认同)