【问题标题】:Xamarin Log.v equivalent to print to console / logcatXamarin Log.v 相当于打印到控制台/logcat
【发布时间】:2017-06-14 09:00:20
【问题描述】:

如何在 Xamarin 中使用 Log.v() 或等效项?我正在 Xamarin/Visual Studio 中开发一个 Android 应用程序,我想输出一些日志,例如就像 Android 中的 Log.v() 一样,然后我可以通过 adb shell logcat 获得它。当我尝试使用

   Log.v("test");

Visual Studio 声明:“日志”无法访问其保护级别。

Debug.WriteLine("");只写入VS日志,不会出现在Logcat中。

有什么建议吗?谢谢!

更新:添加了代码。

        using Xamarin.Forms;
        using System;
        using System.Diagnostics;
        using Android.Util.Log;

        namespace xf2
        {
            public partial class xf2Page : ContentPage
            {
                public xf2Page()
                {
                    InitializeComponent();
                    Log.Debug("SO", "Debug");
                    Log.Error("SO", "Error");
                    Log.Info("SO", "Info");
                    Log.Warn("SO", "Warn");
                }
            }
        }

【问题讨论】:

  • using Android.Util; 不是using Android.Util.Log;

标签: android xamarin xamarin.android xamarin.forms


【解决方案1】:

Log 位于 Android.Util 命名空间中,并且是特定于平台的。

using Android.Util;

然后可以使用Log输出到logcat:

Log.Verbose("SO", "Verbose");
Log.Debug("SO", "Debug");
Log.Error("SO", "Error");
Log.Info("SO", "Info");
Log.Warn("SO", "Warn");

要从基于 Forms 的 PCL/NStd 库中调用 Log,您可以使用依赖项服务:

回复:https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/dependency-service/

依赖服务接口:

public interface ILogInterface
{
    void Verbose(string TAG, string message);
    void Info(string TAG, string message);
    void Debug(string TAG, string message);
    void Error(string TAG, string message);
    void Warn(string TAG, string message);
}

Android 实现:

public class LogImplementation : ILogInterface
{
    public void Debug(string TAG, string message)
    {
        L.Debug(TAG, message);
    }

    public void Error(string TAG, string message)
    {
        L.Error(TAG, message);
    }

    public void Info(string TAG, string message)
    {
        L.Info(TAG, message);
    }

    public void Verbose(string TAG, string message)
    {
        L.Verbose(TAG, message);
    }

    public void Warn(string TAG, string message)
    {
        L.Warn(TAG, message);
    }
}

注意:应用程序集级依赖发现属性:

[assembly: Xamarin.Forms.Dependency(typeof(ILogInterface))]

表格用法:

var Log = DependencyService.Get<ILogInterface>();
Log.Debug("SO", "record someting in logcat");

【讨论】:

  • VS 状态到“使用 Android.Util”:使用指令是不必要的。 VS 状态为“Log.Info”和其他:“Log”无法访问其保护级别。
  • 然后VS声明:Android这个名字在当前上下文中不存在。更新了我上面的代码,忘了提到我正在为此使用 Xamarin Forms。也许这就是问题所在?
  • @frazer87 您是否尝试在基于 Forms 的 PCL/NStd 库中使用 Android.Util.Log?这是一个特定于平台的 SDK,您需要使用依赖服务从 Forms 访问它。
  • 这正是我想要达到的目标。为我工作。非常感谢!!
猜你喜欢
  • 1970-01-01
  • 2016-09-21
  • 1970-01-01
  • 1970-01-01
  • 2016-11-26
  • 2012-02-07
  • 2015-05-04
  • 2016-11-19
  • 2018-07-14
相关资源
最近更新 更多