How to Integrate Logging into Your Application

This entry is part 1 of 2 in the series Getting Started With ClearInsights

Getting Started

  • Create an account: Get started by creating a free account. Sign Up
  • ApiKey: Get your account ApiKey
  • Client Secret: A client secret is unique to a product and environment. Create or use an existing product, then create or use an existing environment. View Your Products

ASP.Net Core Logging

SDK

dotnet add package ClearInsights

Logging

Add ClearInsights LoggerProgram.cs

using ClearInsights;

builder.Logging.AddClearInsightsLogger(configuration =>
 {
     configuration.ApiKey = "{ApiKey}";
     configuration.Secret = "{Environment Client Secret}";
     configuration.ApplicationName = "{Application Name}";
 });

Example use case – AboutModel.cs

public class AboutModel : PageModel
{
    private readonly ILogger _logger;

    public AboutModel(ILogger<AboutModel> logger)
    {
        _logger = logger;
    }

    public void OnGet()
    {
        try
        {
            //Some code here
            _logger.LogInformation("About page visited at {DT}", 
              DateTime.UtcNow.ToLongTimeString());
        }
        catch(Exception ex)
        {
            _logger.LogError(ex, "{Error Message}");
        }
    }
}

Global Error Handling

Add ClearInsights global exception handling – Program.cs

using ClearInsights;

app.UseClearInsightsExceptionHandling(options =>
 {
     //Add to extend the error handler and add additional logic.
     //Add logic like custom HTTP response, etc...
     options.OnError += (sender, arg) =>
     {
         var response = "Oops something went wrong";
         arg.HttpContext.Response.ContentType = "text/html";
         arg.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
         arg.HttpContext.Response.WriteAsync(response);
     };
 });

.Net Core Logging

SDK

dotnet add package ClearInsights

Logging

Add ClearInsights Logger – Program.cs

using ClearInsights;

using IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureLogging(builder =>
        builder.ClearProviders()
            .AddClearInsightsLogger(configuration =>
            {
                configuration.ApiKey = "{ApiKey}";
                configuration.Secret = "{Client Secret}";
                configuration.ApplicationName = "{Application Name}";
            }))
            .Build();

Example use case – MyService.cs

public interface IMyService
{
    Task Execute();
}

public class MyService : IMyService
{
    private readonly ILogger _logger;

    public MyService(ILogger<AboutModel> logger)
    {
        _logger = logger;
    }

    public async Task Execute()
    {
        try
        {
            //Some code here
            _logger.LogInformation("Executed at {DT}", 
              DateTime.UtcNow.ToLongTimeString());
        }
        catch(Exception ex)
        {
            _logger.LogError(ex, "{Error Message}");
        }
    }
}

Global Error Handling

Add ClearInsights global exception handling – Program.cs

using ClearInsights;

System.AppDomain.CurrentDomain.UseClearInsightsExceptionHandling(host.Services.GetRequiredService<ILogger<Program>>());

Python Logging

SDK

pip install ClearInsights

Logging

Add ClearInsights logging by importing the latest PyPi package

import ClearInsights

def main():    
    log = ClearInsights.Logger(apiKey = "${ApiKey}", 
                               clientSecret = "${ClientSecret}", 
                               applicationName = "${ApplicationName}")

    log.LogInformation("Information Info")
    log.LogDebug("Debug Info")  
    log.LogTrace("Trace Info")
    log.LogError(err)
    log.LogWarning("Warning Info")   

if __name__ == "__main__":
    main()

Global Error Handling

import ClearInsights
import sys

def my_except_hook(exctype, error, error_traceback):   
    log = ClearInsights.Logger(apiKey = "${ApiKey}", 
                               clientSecret = "${ClientSecret}", 
                               applicationName = "${ApplicationName}")

    log.LogError(error)

def main():    
    sys.excepthook = my_except_hook 

if __name__ == "__main__":
    main()
Series NavigationHow to Integrate Monitoring into Your Application >>

Leave a Reply