MobileLogging.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. private static Logger CheckLogger()
  19. {
  20. if (_logger == null)
  21. {
  22. var libraryPath = OperatingSystem.IsIOS()
  23. ? Environment.GetFolderPath(Environment.SpecialFolder.Resources)
  24. : Environment.GetFolderPath(Environment.SpecialFolder.Personal);
  25. var filename = $"{DateTime.Today:yyyy-MMM-dd}.prsmobile";
  26. _logfilenameincludingpath = Path.Combine(libraryPath, filename);
  27. var files = Directory.GetFiles(libraryPath, "*.prsmobile");
  28. foreach (var file in files)
  29. {
  30. if (!String.Equals(filename.ToUpper(), Path.GetFileName(file).ToUpper()))
  31. File.Delete(file);
  32. }
  33. _logger = new LoggerConfiguration()
  34. .WriteTo.File(_logfilenameincludingpath)
  35. .CreateLogger();
  36. }
  37. return _logger;
  38. }
  39. public static void Log(LogType type, string entitytype, string message, string page)
  40. {
  41. CheckLogger()
  42. .Information("{Type} {Entity} {Message} {Page}", type, entitytype, message, page);
  43. }
  44. public static void Log(string message)
  45. {
  46. CheckLogger()
  47. .Information("{Log}", message);
  48. }
  49. public static void Log(Exception exception, String tag = "")
  50. {
  51. CheckLogger();
  52. if (String.IsNullOrWhiteSpace(tag))
  53. _logger.Error("{Message} {StackTrace}",exception.Message, exception.StackTrace);
  54. else
  55. _logger.Error("{Tag} {Message} {StackTrace}", tag, exception.Message, exception.StackTrace);
  56. }
  57. public static String ReadLog()
  58. {
  59. CheckLogger();
  60. return File.Exists(_logfilenameincludingpath)
  61. ? File.ReadAllText(_logfilenameincludingpath)
  62. : "";
  63. }
  64. }
  65. }