MobileLogging.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using Serilog;
  2. using Serilog.Core;
  3. namespace InABox.Avalonia
  4. {
  5. public enum LogType
  6. {
  7. Query,
  8. Save,
  9. Delete,
  10. Validate,
  11. UIUpdate,
  12. BackgroundProcess
  13. }
  14. public static class MobileLogging
  15. {
  16. private static Logger _logger = null;
  17. private static string _logfilenameincludingpath;
  18. public delegate void ExceptionHandler(Exception ex, string? tag);
  19. public static event ExceptionHandler? LogException;
  20. private static Logger CheckLogger()
  21. {
  22. if (_logger == null)
  23. {
  24. var libraryPath = OperatingSystem.IsIOS()
  25. ? Environment.GetFolderPath(Environment.SpecialFolder.Resources)
  26. : Environment.GetFolderPath(Environment.SpecialFolder.Personal);
  27. var filename = $"{DateTime.Today:yyyy-MMM-dd}.prsmobile";
  28. _logfilenameincludingpath = Path.Combine(libraryPath, filename);
  29. var files = Directory.GetFiles(libraryPath, "*.prsmobile");
  30. foreach (var file in files)
  31. {
  32. if (!String.Equals(filename.ToUpper(), Path.GetFileName(file).ToUpper()))
  33. File.Delete(file);
  34. }
  35. _logger = new LoggerConfiguration()
  36. .WriteTo.File(_logfilenameincludingpath)
  37. .CreateLogger();
  38. }
  39. return _logger;
  40. }
  41. public static void Log(LogType type, string entitytype, string message, string page)
  42. {
  43. CheckLogger()
  44. .Information("{Type} {Entity} {Message} {Page}", type, entitytype, message, page);
  45. }
  46. public static void Log(string message)
  47. {
  48. CheckLogger()
  49. .Information("{Log}", message);
  50. }
  51. public static void LogError(string message)
  52. {
  53. CheckLogger()
  54. .Error("{Log}", message);
  55. }
  56. public static void Log(Exception exception, String tag = "")
  57. {
  58. LogException?.Invoke(exception, tag);
  59. }
  60. public static void LogExceptionMessage(Exception exception, string tag = "")
  61. {
  62. CheckLogger();
  63. if (String.IsNullOrWhiteSpace(tag))
  64. _logger.Error("{Message} {StackTrace}",exception.Message, exception.StackTrace);
  65. else
  66. _logger.Error("{Tag} {Message} {StackTrace}", tag, exception.Message, exception.StackTrace);
  67. }
  68. public static String ReadLog()
  69. {
  70. CheckLogger();
  71. return File.Exists(_logfilenameincludingpath)
  72. ? File.ReadAllText(_logfilenameincludingpath)
  73. : "";
  74. }
  75. }
  76. }