BaseLog.cs
1 using Utils; 2 3 namespace Logging 4 { 5 public interface ILog 6 { 7 void Log(string message); 8 void Debug(string message = "", int skipFrames = 0); 9 void Error(string message); 10 void Raw(string message); 11 void AddStringReplace(string from, string to); 12 LogFile CreateSubfile(string addName, string ext = "log"); 13 string GetFullName(); 14 } 15 16 public abstract class BaseLog : ILog 17 { 18 public static bool EnableDebugLogging { get; set; } = false; 19 20 private readonly NumberSource subfileNumberSource = new NumberSource(0); 21 private readonly List<BaseLogStringReplacement> replacements = new List<BaseLogStringReplacement>(); 22 private LogFile? logFile; 23 24 public BaseLog() 25 { 26 IsDebug = 27 EnableDebugLogging || 28 !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("LOGDEBUG")) || 29 !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("DEBUGLOG")); 30 } 31 32 protected bool IsDebug { get; private set; } 33 34 public abstract string GetFullName(); 35 36 public LogFile LogFile 37 { 38 get 39 { 40 if (logFile == null) logFile = new LogFile(GetFullName() + ".log"); 41 return logFile; 42 } 43 } 44 45 public virtual void Log(string message) 46 { 47 LogFile.Write(ApplyReplacements(message)); 48 } 49 50 public void Debug(string message = "", int skipFrames = 0) 51 { 52 if (IsDebug) 53 { 54 var callerName = DebugStack.GetCallerName(skipFrames); 55 Log($"(debug)({callerName}) {message}"); 56 } 57 } 58 59 public virtual void Error(string message) 60 { 61 var msg = $"[ERROR] {message}"; 62 Console.WriteLine(msg); 63 Log(msg); 64 } 65 66 public void Raw(string message) 67 { 68 LogFile.Write(message); 69 } 70 71 public virtual void AddStringReplace(string from, string to) 72 { 73 if (string.IsNullOrWhiteSpace(from)) return; 74 if (replacements.Any(r => r.From == from)) return; 75 replacements.Add(new BaseLogStringReplacement(from, to)); 76 } 77 78 public virtual void Delete() 79 { 80 File.Delete(LogFile.Filename); 81 } 82 83 public LogFile CreateSubfile(string addName, string ext = "log") 84 { 85 addName = addName 86 .Replace("<", "") 87 .Replace(">", ""); 88 89 return new LogFile($"{GetFullName()}_{GetSubfileNumber()}_{addName}.{ext}"); 90 } 91 92 protected string ApplyReplacements(string str) 93 { 94 if (IsDebug) return str; 95 foreach (var replacement in replacements) 96 { 97 str = replacement.Apply(str); 98 } 99 return str; 100 } 101 102 private string GetSubfileNumber() 103 { 104 return subfileNumberSource.GetNextNumber().ToString().PadLeft(6, '0'); 105 } 106 } 107 108 public class BaseLogStringReplacement 109 { 110 public BaseLogStringReplacement(string from, string to) 111 { 112 From = from; 113 To = to; 114 115 if (string.IsNullOrEmpty(from) || string.IsNullOrEmpty(to) || from == to) throw new ArgumentException(); 116 } 117 118 public string From { get; } 119 public string To { get; } 120 121 public string Apply(string msg) 122 { 123 return msg.Replace(From, To); 124 } 125 } 126 }