EFLoggerProvider.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. using Microsoft.Extensions.Logging;
  2. using System;
  3. namespace DBHelper
  4. {
  5. public class EfLoggerProvider : ILoggerProvider
  6. {
  7. public ILogger CreateLogger(string categoryName) => new EfLogger(categoryName);
  8. public void Dispose()
  9. { }
  10. }
  11. public class EfLogger : ILogger
  12. {
  13. private readonly string _categoryName;
  14. public EfLogger(string categoryName) => this._categoryName = categoryName;
  15. public bool IsEnabled(LogLevel logLevel) => true;
  16. public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
  17. {
  18. //ef core执行数据库查询时的categoryName为Microsoft.EntityFrameworkCore.Database.Command,日志级别为Information
  19. if (_categoryName != "Microsoft.EntityFrameworkCore.Database.Command" ||
  20. logLevel != LogLevel.Information) return;
  21. var logContent = formatter(state, exception);
  22. //TODO: 拿到日志内容想怎么玩就怎么玩吧
  23. //Console.WriteLine();
  24. //Console.ForegroundColor = ConsoleColor.Green;
  25. //Console.WriteLine(logContent);
  26. //Console.ResetColor();
  27. }
  28. public IDisposable BeginScope<TState>(TState state) => null;
  29. }
  30. }