EFLoggerProvider.cs 1.4 KB

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