跨平台登录Xamarin

时间:2014-03-17 19:19:36

标签: ios xamarin.ios xamarin.android xamarin

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

由于

2 个答案:

答案 0 :(得分: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兼容库的CRUD提供程序包装器(适用于iOS,Android和WP8): 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>())
                    )));

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

DependencyResolver.Current.RegisterService<ILogService, LogService>();

答案 1 :(得分:4)

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

     Mvx.RegisterSingleton<ILogging >(new Logging());
之后,您可以从核心项目轻松访问它

    Mvx.Resolve<ILogging>();