MobileLogging.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. Directory.CreateDirectory(libraryPath);
  30. var files = Directory.GetFiles(libraryPath, "*.prsmobile");
  31. foreach (var file in files)
  32. {
  33. if (!String.Equals(filename.ToUpper(), Path.GetFileName(file).ToUpper()))
  34. File.Delete(file);
  35. }
  36. _logger = new LoggerConfiguration()
  37. .WriteTo.File(_logfilenameincludingpath)
  38. .CreateLogger();
  39. }
  40. return _logger;
  41. }
  42. public static void Log(LogType type, string entitytype, string message, string page)
  43. {
  44. CheckLogger()
  45. .Information("{Type} {Entity} {Message} {Page}", type, entitytype, message, page);
  46. }
  47. public static void Log(string message)
  48. {
  49. CheckLogger()
  50. .Information("{Log}", message);
  51. }
  52. public static void LogError(string message)
  53. {
  54. CheckLogger()
  55. .Error("{Log}", message);
  56. }
  57. public static void Log(Exception exception, String tag = "")
  58. {
  59. LogException?.Invoke(exception, tag);
  60. }
  61. public static void LogExceptionMessage(Exception exception, string tag = "")
  62. {
  63. CheckLogger();
  64. if (String.IsNullOrWhiteSpace(tag))
  65. _logger.Error("{Message} {StackTrace}",exception.Message, exception.StackTrace);
  66. else
  67. _logger.Error("{Tag} {Message} {StackTrace}", tag, exception.Message, exception.StackTrace);
  68. }
  69. public static String ReadLog()
  70. {
  71. CheckLogger();
  72. return File.Exists(_logfilenameincludingpath)
  73. ? File.ReadAllText(_logfilenameincludingpath)
  74. : "";
  75. }
  76. }
  77. }