using System; using System.IO; using System.Text; namespace Flyinsono.Client.Test { public class DefaultLogEngine : LogEngine { private const string InfoTag = "I ; "; private const string DebguTag = "D ; "; private const string WarnTag = "W ; "; private const string ErrorTag = "E ; "; private const string VerboseTag = "V ; "; private const string UserOperationTag = "U ; "; private StreamWriter _logWriter; private readonly object _mutex = new object(); public static string DataFolder; private DateTime _date; private bool _disposed; public DefaultLogEngine() { } ~DefaultLogEngine() { //Dispose the StreamWriter when dispose. DoDispose(); } private void DoDispose() { if (!_disposed) { _disposed = true; } } protected void InitializeLogger() { var logDirectory = Path.Combine(DataFolder, "Logs"); if (!Directory.Exists(logDirectory)) { Directory.CreateDirectory(logDirectory); } var now = DateTime.Now; var logTag = $"{now:yyyyMMddHHmmss}_{now.Millisecond:d3}"; var logFileName = $"Log_{logTag}.log"; var logFilePath = Path.Combine(logDirectory, logFileName); if (!File.Exists(logFilePath)) { _logWriter?.Close(); var logFileStream = new FileStream(logFilePath,FileMode.Create,FileAccess.ReadWrite,FileShare.ReadWrite); _logWriter = new StreamWriter(logFileStream); } else { _logWriter?.Close(); var logFileStream = new FileStream(logFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); logFileStream.Position = logFileStream.Length; _logWriter = new StreamWriter(logFileStream); } } public override void Write(LogLevel level, string msg) { lock (_mutex) { if (DateTime.Today != _date) { InitializeLogger(); _date = DateTime.Today; } try { var message = RecombinateMessage(level, msg); WriteMessage(message); } catch (Exception) { // There is exception during writing log, so just ignore } } } protected void WriteMessage(string message) { _logWriter.WriteLine(message); _logWriter.Flush(); } protected string RecombinateMessage(LogLevel level, string msg) { var now = DateTime.Now; StringBuilder sb = new StringBuilder(); sb.Append( $"[{now:yyyyMMddHHmmss},{now.Millisecond:d3}]-"); string message = msg; if (level == LogLevel.Error) { sb.Append(ErrorTag); } else if (level == LogLevel.Warn) { sb.Append(WarnTag); } else if (level == LogLevel.Info) { sb.Append(InfoTag); } else if (level == LogLevel.Verbose) { sb.Append(VerboseTag); } else if (level == LogLevel.Debug) { sb.Append(DebguTag); } else if (level == LogLevel.UserOperation) { sb.Append(UserOperationTag); } sb.Append(message); return sb.ToString(); } public override void Dispose() { DoDispose(); GC.SuppressFinalize(this); } } }