Documentation

Add logging interceptor

Nomirun SDK contains Logging interceptor, which is an interceptor for class methods is a design pattern or tool used to capture and log method-level activity in applications. It intercepts the execution of a class method via dynamic proxies and adds logging functionality before, during, or after the method is executed.

Imagine you have this interface and implementation:

public interface ICalculator
{
    int Sum(int a, int b);
}

public class Calculator: ICalculator
{
    public int Sum(int a, int b)
    {
        return a + b;
    }
}

How would you add some error logging to the method without an interceptor?

public class Calculator: ICalculator
{
    private readonly ILogger<Calculator> _logger;

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

    public int Sum(int a, int b)
    {
        try
        {    
            var result = a + b;    
            return result;
        }
        catch(Exception ex)
        {
            _logger.LogInformation(ex.Message);
        }
    }
}

That is a lot of code that could be repeated throughout your codebase right? You can easily use a logging interceptor that Nomirun SDK supports. To achieve the same capability, you can do:

public class Calculator: ICalculator
{
    [AddLogging]
    public int Sum(int a, int b)
    {
        return a + b;
    }
}

It is required that you use interfaces (eg. ICalculator above) to abstract your classes as those will be correctly registered with interceptor using dynamic proxy. Also, to register the class in the DI container you can use:

services.AddScoped<ICalculator,Calculator>();