netcore3.0 Logging 日志系统(三)

上篇介绍了netcore里面的几个日志提供器

我们看下如何简单的使用:

var services = new ServiceCollection();
            services.AddLogging(builder => { builder.AddConsole(); });
            var provider = services.BuildServiceProvider();

            var logger = provider.GetService<ILogger<Program>>();
            logger.LogInformation("test");
            Console.Read();

 

我们也可以自己扩展:

public class MyLogger : ILogger
    {
        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            Console.WriteLine(formatter(state, exception));
        }

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

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

    public class MyLoggerProvider : ILoggerProvider
    {
        public void Dispose()
        {
            
        }

        public ILogger CreateLogger(string categoryName)
        {
            return new MyLogger();
        }
    }

    public static class MyLoggerExtension
    {
        public static ILoggingBuilder AddMyLogger(this ILoggingBuilder builder)
        {
            builder.AddConfiguration();
            builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<ILoggerProvider, MyLoggerProvider>());
            return builder;
        }
    }
class Program
    {
        static void Main(string[] args)
        {
            var services = new ServiceCollection();
            services.AddLogging(builder => { builder.AddMyLogger(); });
            var provider = services.BuildServiceProvider();

            var logger = provider.GetService<ILogger<Program>>();
            logger.LogInformation("test");
            Console.Read();
        }
    }

 

posted @ 2020-03-21 18:29  蓝平凡  阅读(813)  评论(0编辑  收藏  举报