Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Log.v equivalent to print to console / logcat

How can I use Log.v() or an equivalent in Xamarin? I am developing an Android App in Xamarin/Visual Studio and I want to output some logs, e.g. like with Log.v() in Android, which i then can get via adb shell logcat. When I try to use

   Log.v("test");

Visual Studio states: ‚Log‘ is inaccessible to its protection level.

Debug.WriteLine(""); only writes to VS log, it does not appear in Logcat.

Any suggestions? Thanks!

Update: Code added.

        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");
                }
            }
        }
like image 571
frazer87 Avatar asked Feb 04 '23 06:02

frazer87


1 Answers

Log is in the Android.Util namespace and is platform-specific.

using Android.Util;

Then you can use Log to output to logcat:

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

To call Log from a Forms-based PCL/NStd library, you could use a dependency service:

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

Dependency service Interface:

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 implementation:

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);
    }
}

Note: Apply the assembly-level dependency discovery attribute:

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

Forms Usage:

var Log = DependencyService.Get<ILogInterface>();
Log.Debug("SO", "record someting in logcat");
like image 117
SushiHangover Avatar answered Feb 06 '23 18:02

SushiHangover