1

是否可以在 .Net Framework 控制台应用程序中使用 ILogger 日志?我搜索了很多,但我找不到样本。这是我到目前为止想出的

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

我不知道如何添加 LoggerProvider。是否已经为 .Net Framework 的 Console 和 File 实现了提供程序,或者它们仅适用于 Core?

我需要实现自己的提供程序吗?

4

1 回答 1

0
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);
        //}
    }
}
于 2019-07-25T07:43:53.207 回答