// Spludlow Software // Copyright © Samuel P. Ludlow 2020 All Rights Reserved // Distributed under the terms of the GNU General Public License version 3 // Distributed WITHOUT ANY WARRANTY; without implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE // https://www.spludlow.co.uk/LICENCE.TXT // The Spludlow logo is a registered trademark of Samuel P. Ludlow and may not be used without permission // v1.14 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace Spludlow { public class LogFile : IDisposable { public string Filename; private long Start; private DateTime StartTime; private StreamWriter Writer; public LogFile(string name) { if (name.Contains(@"\") == true && name.Contains(":") == true) this.Filename = name; else this.Filename = Spludlow.Config.ProgramData + @"\Logs\" + name; this.Writer = new StreamWriter(this.Filename, true); this.Writer.AutoFlush = true; this.Start = this.Writer.BaseStream.Length; this.StartTime = DateTime.Now; this.Append("START\t" + this.Start.ToString()); } public void Dispose() { this.Close(); } public void Close() { if (this.Writer == null) return; this.Append("STOP\t" + Spludlow.Text.TimeTook(this.StartTime)); this.Writer.Close(); this.Writer = null; } public string ReadSession() { if (this.Writer != null) throw new ApplicationException("You can only read a log file session after it has been closed."); using (StreamReader reader = new StreamReader(this.Filename)) { reader.BaseStream.Position = this.Start; return reader.ReadToEnd(); } } public void Append(string subject) { this.AppendWriter(subject, null); } public void Append(string subject, string body) { this.AppendWriter(subject, body); } public void Append(string subject, Exception ee) { this.AppendWriter(subject + "\t" + ee.Message, ee.ToString()); } private void AppendWriter(string subject, string body) { if (this.Writer == null) return; StringBuilder text = new StringBuilder(); text.Append(DateTime.Now.ToString()); text.Append("\t"); text.Append(subject); text.AppendLine(); if (body != null) { text.AppendLine(body); text.AppendLine(); } lock (this.Writer) this.Writer.Write(text.ToString()); } } }