TinyInsights is a open-source library for .NET MAUI to track analytics data to Application Insights. The default way to use it is with the IInsights interface that has customized methods to get the most out of the library. But in some cases, you may want to use the ILogger interface instead, because that is pretty standard in .NET applications and you may already have it in your app when you want to start using TinyInsights. And then it will be easier to change the implementation for it. You can configure the app to use ILogger in two ways.
If you just want to use the ILogger interface you can use the UseTinyInsightsAsILogger method.
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.UseTinyInsightsAsILogger("{Your-Application-Insights-ConnectionString}");
If you want to use both the default IInsights interface and ILogger you can do that too. Then you can use the UseTinyInsights method and after that register the ILogger interface to the service collection (dependency injection container).
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.UseTinyInsights("{Your-Application-Insights-ConnectionString}");
builder.Services.AddSingleton<ILogger>((serviceProvider) =>
{
var insights = serviceProvider.GetRequiredService<IInsights>();
var providers = insights.GetProviders();
if (providers.Any())
{
return (ILogger)providers.First();
}
throw new InvalidOperationException("No insights provider found");
});
Then you can use it like below:
private readonly ILogger logger;
public class MainViewModel(ILogger logger)
{
this.logger = logger;
}
Track page views
By default, page views are automatically tracked. But you can turn that off, and do it manually if you prefer.
logger.LogTrace("MainView");
Track event
logger.LogInformation("EventButton");
Track error
logger.LogError(ex, ex.Message);
Track debug info
LogDebug will only work with the debugger attached because it is using Debug.WriteLine.
logger.LogDebug("Debug message");
To read more about TinyInsights, go to the repository at GitHub, (https://github.com/dhindrik/TinyInsights.Maui)