Thursday, 5 April 2018

How to use a file to store all your logs in Xamrin Android App

Background

You can see the debug logs in the Device Log tab in Visual studio but you need to connect a USB to your android phone (not needed if you are using an emulator). However this is for realtime debugging and will not be useful to check logs that were present couple of hours back. In this post I will show you how you can log into a file in the android sd card so that you can refer it at any point in time to see what has happened.


How to use a file to store all your logs in Xamrin Android App

You can log to a file using following code snippet -

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

Let's uderstand whats happening here -

In the constructor we are getting the external storage directory and creating a file called "log.txt" there. We are checking if the file already exists and if it does not we create it. Now anyone who want to log to this file can simple create an instance of LogUtils and call Log method on it.

You can do this on OnCreate of your main activity. For me external storage file is - /storage/emulated/0 so my complete log file path is /storage/emulated/0/log.txt

Make sure you have provided appropriate permissions in the manifest file -

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


Related Links



t> UA-39527780-1 back to top