如何在 Xamarin Android 应用程序中将日志输出到 SD 卡上的文件?

How to output log to file on SD Card in Xamarin Android app?

我有一个 Xamarin Android 应用程序,整个应用程序中都有 Debug.WriteLine 语句。这些语句出现在 Xamarin 控制台中,但我希望它们也被附加到 phone SD 卡上的日志文件中。

我想我可以开发自己的解决方案,但我想知道是否有内置方法可以做到这一点?

Android 有一个内置的 logging 函数供您使用,Android.Util.Log

string tag = "myapp";

Log.Info (tag, "this is an info message");
Log.Warn (tag, "this is a warning message");
Log.Error (tag, "this is an error message");

我认为没有内置的方法可以做到这一点,但一个简单的代码可以为您做到这一点 -

using System;
namespace Com.Osfg
{
    public class LogUtils
    {
        String logFilePath = null;

        public LogUtils()
        {
            String path = Android.OS.Environment.ExternalStorageDirectory.Path;
            logFilePath = System.IO.Path.Combine(path, "log.txt");
            if(!System.IO.File.Exists(logFilePath))
            {
                using (System.IO.StreamWriter writer = new System.IO.StreamWriter(logFilePath, true))
                {
                    writer.WriteLine("Starting logging at " + DateTime.Now.ToString());
                }
            }
        }

        public void Log(String message)
        {
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(logFilePath, true))
            {
                writer.WriteLine(DateTime.Now.ToString() + " : " + message);
            }
        }
    }
}