LoggerImpl.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using XGame.Framework.Utils;
  2. using LitJson;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. namespace XGame.Framework.Logger
  7. {
  8. internal class LoggerImpl : ILogger, ILogFlushable, IDisposable
  9. {
  10. private ILogColors _colors;
  11. private WriterRepository _writerRepository;
  12. private JsonData _jsonData;
  13. private JsonData jsonData => _jsonData ?? (_jsonData = new JsonData());
  14. public LoggerImpl(ILogColors logColors, WriterRepository writerRepository)
  15. {
  16. _colors = logColors;
  17. _writerRepository = writerRepository;
  18. }
  19. public void Initialize()
  20. {
  21. if (_writerRepository != null)
  22. {
  23. var logDirectory = LogDefine.LogRootPath;
  24. if (!Directory.Exists(logDirectory))
  25. {
  26. Directory.CreateDirectory(logDirectory);
  27. }
  28. }
  29. }
  30. public string Log(LogLevel level, string format, params object[] args)
  31. {
  32. var entity = new LogCodeEntity()
  33. {
  34. log_level = level.ToString(),
  35. log_info = format.Format(args),
  36. };
  37. if (_writerRepository != null)
  38. {
  39. _writerRepository.GetWriter(LogType.Code).Write(entity.ToWriteString());
  40. }
  41. var logInfo = entity.ToConsoleString();
  42. if (_colors != null)
  43. {
  44. return _colors.Format(level, logInfo);
  45. }
  46. return logInfo;
  47. }
  48. public string Event(string type, string id, Dictionary<string, string> infos)
  49. {
  50. var entity = new LogEventEntity()
  51. {
  52. event_type = type,
  53. event_id = id,
  54. info = infos
  55. };
  56. if (_writerRepository != null)
  57. {
  58. _writerRepository.GetWriter(LogType.Event).Write(entity.ToWriteString(jsonData));
  59. }
  60. var logInfo = entity.ToConsoleString();
  61. if (_colors != null)
  62. {
  63. return _colors.Format(LogLevel.Event, logInfo);
  64. }
  65. return logInfo;
  66. }
  67. public void Dispose()
  68. {
  69. (_writerRepository as IDisposable)?.Dispose();
  70. }
  71. void ILogFlushable.Flush(LogType logType)
  72. {
  73. if (_writerRepository == null)
  74. return;
  75. _writerRepository.GetWriter(logType).Flush();
  76. }
  77. }
  78. }