SqlLogger.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 DW5S.Repostory
  8. {
  9. public class SqlLoggerProvider : ILoggerProvider
  10. {
  11. public ILogger CreateLogger(string categoryName) => new SqlLogger(categoryName);
  12. public void Dispose() { }
  13. }
  14. public class SqlLogger : ILogger
  15. {
  16. private readonly string categoryName;
  17. public SqlLogger(string categoryName) => this.categoryName = categoryName;
  18. public IDisposable BeginScope<TState>(TState state) => null;
  19. public bool IsEnabled(LogLevel logLevel) => true;
  20. public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
  21. {
  22. if (exception != null)
  23. Serilog.Log.Error(exception, formatter(state, exception));
  24. else
  25. {
  26. if (categoryName == "Microsoft.EntityFrameworkCore.Database.Command")
  27. {
  28. if (logLevel == LogLevel.Warning)
  29. {
  30. var logContent = formatter(state, exception);
  31. Serilog.Log.Warning(exception, logContent);
  32. }
  33. else if (logLevel == LogLevel.Error)
  34. {
  35. var logContent = formatter(state, exception);
  36. Serilog.Log.Error(exception, logContent);
  37. }
  38. else
  39. {
  40. var logContent = formatter(state, exception);
  41. Serilog.Log.Information(logContent);
  42. }
  43. }
  44. }
  45. }
  46. }
  47. }