3

Is it possible to use an ILogger log in a .Net Framework console app? I searched a lot but I wasn't able to find a sample. This is what I came up with so far

        var loggerFactory = new LoggerFactory();
        //loggerFactory.AddProvider();
        var logger = loggerFactory.CreateLogger("Category");
        logger.LogInformation("This is a log line");

I don't know how to add a LoggerProvider. Are there providers already implemented for Console and File for .Net Framework or they are only for Core?

Do I need to implement my own providers?

Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
Nicolae Daian
  • 1,065
  • 3
  • 18
  • 39

1 Answers1

1
using Microsoft.Extensions.Logging;

namespace Test
{   
    class Program
    {
        // Single-Threaded Apartment required for OAuth2 Authz Code flow (User Authn) to execute for this demo app
        [STAThread]
        static void Main(string[] args)
        {
            var log = new VerboseDiagnosticsTraceWriter();
            log.LogInformation($"test");
        }
    }
}

using Microsoft.Extensions.Logging;
using System;

namespace Test
{
    internal class VerboseDiagnosticsTraceWriter : ILogger
    {


        public IDisposable BeginScope<TState>(TState state)
        {
            return null;
        }

        public bool IsEnabled(LogLevel logLevel)
        {
            return true;
        }

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            //System.Diagnostics.Debug.WriteLine($"{logLevel} {state.ToString()}");
            Console.WriteLine($"[{DateTime.Now}] {logLevel} {state.ToString()}");
        }

        //public override void Trace(Microsoft.Azure.WebJobs.Host.TraceEvent traceEvent)
        //{
        //    System.Diagnostics.Debug.WriteLine(traceEvent.Message);
        //}
    }
}
Javier
  • 21
  • 1