StringLoggerFactory.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright (c) .NET Foundation. All rights reserved.
  2. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  3. using System;
  4. using System.Globalization;
  5. using System.Text;
  6. using Microsoft.Extensions.Logging;
  7. namespace Microsoft.AspNetCore.DataProtection
  8. {
  9. internal sealed class StringLoggerFactory : ILoggerFactory
  10. {
  11. private readonly StringBuilder _log = new StringBuilder();
  12. public StringLoggerFactory(LogLevel logLevel)
  13. {
  14. MinimumLevel = logLevel;
  15. }
  16. public LogLevel MinimumLevel { get; set; }
  17. public void AddProvider(ILoggerProvider provider)
  18. {
  19. // no-op
  20. }
  21. public ILogger CreateLogger(string name)
  22. {
  23. return new StringLogger(name, this);
  24. }
  25. public void Dispose()
  26. {
  27. }
  28. public override string ToString()
  29. {
  30. return _log.ToString();
  31. }
  32. private sealed class StringLogger : ILogger
  33. {
  34. private readonly StringLoggerFactory _factory;
  35. private readonly string _name;
  36. public StringLogger(string name, StringLoggerFactory factory)
  37. {
  38. _name = name;
  39. _factory = factory;
  40. }
  41. public IDisposable BeginScope<TState>(TState state)
  42. {
  43. return new DummyDisposable();
  44. }
  45. public bool IsEnabled(LogLevel logLevel)
  46. {
  47. return (logLevel >= _factory.MinimumLevel);
  48. }
  49. public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
  50. {
  51. string message = String.Format(CultureInfo.InvariantCulture,
  52. "Provider: {0}" + Environment.NewLine +
  53. "Log level: {1}" + Environment.NewLine +
  54. "Event id: {2}" + Environment.NewLine +
  55. "Exception: {3}" + Environment.NewLine +
  56. "Message: {4}", _name, logLevel, eventId, exception?.ToString(), formatter(state, exception));
  57. _factory._log.AppendLine(message);
  58. }
  59. private sealed class DummyDisposable : IDisposable
  60. {
  61. public void Dispose()
  62. {
  63. // no-op
  64. }
  65. }
  66. }
  67. }
  68. }