Popular blog tags

How to Logging in Class Libraries with ASP.Net Core

Published

Table of Content

Logging in .NET Core with DI

Logging in .NET Core without DI

Logging in .NET Core without DI 2

Logging in .NET Core with DI

This article describes how to integrate  logger for .Net Core Class Libraries project

Create a logger for your class by passing an ILogger<YourClass> in the constructor exactly like in the sample:

public class MyClass : IMyClass
{ 
    private readonly ILogger<MyClass> _logger; 
    public (ILogger<MyClass> logger) 
    { 
     _logger = logger; 
    }

    public void MyMethod()
    { 
     _logger.LogInformation("a log");
    }
} 

 

Or pass an ILoggerFactory:

public class MyClass: IMyClass
{   
   private readonly ILogger _logger;
   public (ILoggerFactory loggerFactory) 
   {
    _logger = loggerFactory.CreatLogger("MyClass"); 
   }

   public void MyMethod()
   {
     _logger.LogInformation("a log"); 
 }
} 

And resolve your class by Dependency Injection:

services.AddTransient<IMyClass, MyClass>();

Then you can use it in your controller: 


[Route("api/[controller]")] 
public class TodoController : Controller 
{ 
  private readonly IMyClass _myClass;
  private readonly ILogger<TodoController> _logger; 
  public TodoController(IMyClass myClass, ILogger<TodoController> logger)
  { 
   _myClass = myClass;
  _logger = logger; 
  } 
}.

Logging in .NET Core without DI

 

If you want to do it yourself you will need to instantiate a LoggerFactory instance somewhere and configure what providers you want. Then you just need to call CreateLogger to create a instance or use new Logger<T>(ILoggerFactory) to create a logger.

.Net 5.x

 public class DataAnalysisKdataService
    {


        #region Fields
        private readonly ILogger _logger;
        private List<KData> _listKDataResult;
        #endregion


        public DataAnalysisKdataService( int kdataMenuId, List<KData> listKData)
        {
            //https://stackoverflow.com/questions/53235472/logging-in-net-core-without-di
               var factory = LoggerFactory.Create(b => b.AddConsole());
               this._logger = factory.CreateLogger<DataAnalysisKdataService>();

            this._listKData = listKData;
            this._listKDataResult = new List<KData>();
        }



//call 
 /// Process method  come winform  20210908
        /// </summary>
        public void Process()
        {
            bool find;
            string sinfo = "";
            string scode = "";

            int LineKChoiced = 0;

            int kdatacombination = this._kdataMenuId;

            var kdata = this._listKData;

            this._logger.LogInformation($"kdata.Count:{kdata.Count } kdataMenuId:{_kdataMenuId} ");

      

 

 

 

Logging in .NET Core without DI 2

namespace Stockso.BlazorServerSide.Services.StockDataPhysicalDisk
{
    public class StockDataPhysicalDiskHistoryReportSearchService
    {




        #region Fields
        private readonly ILogger _logger;
        private readonly IHttpClientFactory _clientFactory;

        #endregion


        #region Constructors

        public StockDataPhysicalDiskHistoryReportSearchService(
            ILogger<StockDataPhysicalDiskHistoryReportSearchService> logger


            )
        {
            this._logger = logger;



        }

 

 services.AddSingleton<StockDataPhysicalDiskReportSearchService>();

 

Logging in .NET Core without DI 3

public sealed class MyStopwatch : IDisposable
{
    ILogger<Startup> _logger;
    string _message;
    Stopwatch _sw;

    public MyStopwatch(ILogger<Startup> logger, string message)
    {
        _logger = logger;
        _message = message;
        _sw = Stopwatch.StartNew();
    }

    private bool disposed = false;


    public void Dispose()
    {
        if (!disposed)
        {
            _logger.LogInformation("{Message }: {ElapsedMilliseconds}ms",
                                    _message, _sw.ElapsedMilliseconds);

            disposed = true;
        }
    }
}

call

public void Configure(IApplicationBuilder app, ILogger<Startup> logger)
{
    int count = 0;
    app.Use(next => async context =>
    {
        using (new MyStopwatch(logger, $"Time {++count}"))
        {
            await next(context);
        }

    });