CliLogger.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System.CommandLine;
  2. using System.CommandLine.Invocation;
  3. using System.CommandLine.IO;
  4. using System.CommandLine.Rendering;
  5. namespace CustomHostingDemo.Logging
  6. {
  7. public class CliLogger : ICliLogger
  8. {
  9. private readonly IConsole _console;
  10. private readonly IDefaultArgs _args;
  11. public CliLogger(InvocationContext context, IDefaultArgs args)
  12. {
  13. _console = context.Console;
  14. _args = args;
  15. }
  16. public ICliLogger LogContent(string message)
  17. {
  18. return Log(new ContentSpan(message));
  19. }
  20. public ICliLogger LogError(string message)
  21. {
  22. return Log(new ContainerSpan(
  23. ForegroundColorSpan.Red(),
  24. new ContentSpan("[ERROR] "),
  25. new ContentSpan(message),
  26. ForegroundColorSpan.Reset()
  27. ));
  28. }
  29. public ICliLogger LogInfo(string message)
  30. {
  31. if (!_args.Verbose)
  32. {
  33. return this;
  34. }
  35. return Log(new ContainerSpan(
  36. ForegroundColorSpan.LightGray(),
  37. new ContentSpan("[INFO] "),
  38. new ContentSpan(message),
  39. ForegroundColorSpan.Reset()
  40. ));
  41. }
  42. public ICliLogger LogWarning(string message)
  43. {
  44. return Log(new ContainerSpan(
  45. ForegroundColorSpan.Yellow(),
  46. new ContentSpan("[WARN] "),
  47. new ContentSpan(message),
  48. ForegroundColorSpan.Reset()
  49. ));
  50. }
  51. private ICliLogger Log(TextSpan span)
  52. {
  53. _console.Out.WriteLine(span.ToString(OutputMode.Ansi));
  54. return this;
  55. }
  56. }
  57. }