Implement Logging Service in .NET MAUI
Tags: maui, dotnet, logs
Published: 2023-10-19 03:37:19

Hello Devs, In this blog we'll learn that how to implement file based Logging service in .NET MAUI without using any external library/packages.

First of all, add below code in the MainPage.xaml.cs file which is located at the root of project directory.

```
using System.Diagnostics;
using System.Reflection;
using System.Runtime.ExceptionServices;
namespace logs;

public partial class MainPage : ContentPage
{

	public MainPage()
	{
		InitializeComponent();
               
		AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;
	}

	private void CurrentDomain_FirstChanceException(object sender, FirstChanceExceptionEventArgs e)
	{
		if (e.Exception is Exception ex)
		{
			LogException(ex);
		}
	}

	private void LogException(Exception ex)
	{
		string logsFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "app_logs.txt");
		try
		{
            // Get information about the method that caused the exception.        
			StackFrame sf = new StackFrame(1);
			MethodBase method = sf.GetMethod();
			int line = sf.GetFileLineNumber();
 
            // Create a log message with thread ID, timestamp, method information, and the exception message.
       
			string exMsg = Environment.CurrentManagedThreadId + " ~ " + DateTime.Now.ToString() + method.DeclaringType.FullName + "::" + line + "-" + GetErrorMessage(ex);
  
            // Append the log message to the specified log file.
			File.AppendAllText(logsFilePath, exMsg + Environment.NewLine + Environment.NewLine);
		}
		catch (Exception exe)
		{
            // If there's an exception while logging, write the error message to the console.
			Console.WriteLine(exe.Message);
		}
	}

	private string GetErrorMessage(Exception ex)
	{
		if (ex != null)
		{
			string message = ex.StackTrace + " " + ex.Message;
			if (ex.InnerException != null)
			{
				message += "~ Caused By" + GetErrorMessage(ex.InnerException);
			}
			return message;
		}

		return string.Empty;
	}

}

```

---

Let's Understand above Code.

=> AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException :
  - This line subscribes the CurrentDomain_FirstChanceException method to the FirstChanceException event of the current application domain. This event is raised whenever an exception is thrown in the application.

=> LogException(Exception ex) :
   - This method is responsible for logging exceptions to a file.
   - It constructs a log file path (logsFilePath) within the application's base directory and attempts to log the exception information to it.
   - It uses StackFrame to retrieve information about the method that caused the exception, such as the method name and line number.
 
=> GetErrorMessage(Exception ex):
   - This is a recursive method that retrieves the error message and stack trace for an exception, including any inner exceptions.

---

After that use try catch block in the code where you want to get logs if any exception occurs. here we add try-catch block in the MainPage.xaml.cs file for demonstrate.

```
private void OnCounterClicked(object sender, EventArgs e)
	{
		throw new Exception("Counter Button Clicked!");
	}

	private void OnGetFilesClicked(object sender, EventArgs e)
	{
		try
		{
               // there is no any directory exist , so exception will be occured
			string path = "/demo_logs";
			Directory.GetFiles(path);
		}
		catch (Exception ex)
		{
			Console.WriteLine(ex.Message);
		}
	}
```
  
---

=> Logging file location (according to specified path in the code):
   - for windows -->  bin\Debug\net7.0-windows10.0.19041.0\win10-x64\app_logs.txt
   - for MacOs --> bin/Debug/net7.0-maccatalyst/maccatalsyt-x64/[Project_Name].app/Contents/MonoBundle/app_logs.txt

=> Logs : 

![logs file output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6hqpy8pkj2pwxhkjgj64.png)

---

You can find the necessary code in the repository mentioned below.

[GithHub Repository](https://github.com/JayMalli/MAUI-Logging)

Thank you for joining me on this journey of discovery and learning. If you found this blog post valuable and would like to connect further, I'd love to connect with you on LinkedIn. You can find me at [LinkedIn](https://www.linkedin.com/in/jaymalli)

If you have thoughts, questions, or experiences related to this topic, please drop a comment below.