MobileLogging.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.IO;
  3. using Serilog;
  4. using Serilog.Core;
  5. using Xamarin.Forms;
  6. namespace InABox.Mobile
  7. {
  8. public enum LogType
  9. {
  10. Query,
  11. Save,
  12. Delete,
  13. Validate,
  14. UIUpdate,
  15. BackgroundProcess
  16. }
  17. public static class MobileLogging
  18. {
  19. private static Logger _logger = null;
  20. private static string _logfilenameincludingpath;
  21. private static Logger CheckLogger()
  22. {
  23. if (_logger == null)
  24. {
  25. var libraryPath = Device.RuntimePlatform.Equals(Device.iOS)
  26. ? Environment.GetFolderPath(Environment.SpecialFolder.Resources)
  27. : Environment.GetFolderPath(Environment.SpecialFolder.Personal);
  28. var filename = $"{DateTime.Today:yyyy-MMM-dd}.prsmobile";
  29. _logfilenameincludingpath = Path.Combine(libraryPath, filename);
  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 Log(Exception exception, String tag = "")
  53. {
  54. CheckLogger();
  55. if (String.IsNullOrWhiteSpace(tag))
  56. _logger.Error("{Message} {StackTrace}",exception.Message, exception.StackTrace);
  57. else
  58. _logger.Error("{Tag} {Message} {StackTrace}", tag, exception.Message, exception.StackTrace);
  59. }
  60. public static String ReadLog()
  61. {
  62. CheckLogger();
  63. return File.Exists(_logfilenameincludingpath)
  64. ? File.ReadAllText(_logfilenameincludingpath)
  65. : "";
  66. }
  67. }
  68. }