diff options
| author | Mirta <mirta@twine-s.com> | 2020-12-30 16:39:52 +0200 |
|---|---|---|
| committer | Mirta <mirta@twine-s.com> | 2020-12-30 16:39:52 +0200 |
| commit | 00a491d93733d4625ad329b2ba8237f445364b3f (patch) | |
| tree | 4b24c6fa78d7648f4bb7cefafa464bb0b063fec4 /Software/Visual_Studio/Tango.Logging | |
| parent | 124ad4150f80c6846fdee41dbbda9848c105f6e5 (diff) | |
| download | Tango-00a491d9.tar.gz Tango-00a491d9.zip | |
merge
Diffstat (limited to 'Software/Visual_Studio/Tango.Logging')
12 files changed, 120 insertions, 601 deletions
diff --git a/Software/Visual_Studio/Tango.Logging/ApplicationLogFileParser.cs b/Software/Visual_Studio/Tango.Logging/ApplicationLogFileParser.cs index 6bd53f433..2870ce95d 100644 --- a/Software/Visual_Studio/Tango.Logging/ApplicationLogFileParser.cs +++ b/Software/Visual_Studio/Tango.Logging/ApplicationLogFileParser.cs @@ -17,26 +17,16 @@ namespace Tango.Logging List<LogFile> logFiles = new List<LogFile>(); FileLogger logger = LogManager.Default.RegisteredLoggers.FirstOrDefault(x => x.GetType() == typeof(FileLogger)) as FileLogger; - HashSet<string> dateStrings = new HashSet<string>(); - foreach (var file in Directory.GetFiles(FileLogger.DefaultLogsFolder, "*.log").Where(x => (Path.GetFileName(x).StartsWith(logger.Tag) && x != logger.LogFile))) + + String logFile = logger != null ? logger.LogFile : null; + + foreach (var file in Directory.GetFiles(FileLogger.DefaultLogsFolder, "*.log").Where(x => Path.GetFileName(x).StartsWith(logger.Tag) && x != logger.LogFile)) { try { String dateString = Path.GetFileNameWithoutExtension(file).Replace($"{logger.Tag}-", ""); - int indexPos = dateString.IndexOf(FileLogger.FILE_SET_EXTENSION); - int indexOfFile = 0; - if (indexPos > 0) - { - string fileNameIndex = dateString.Substring(indexPos + FileLogger.FILE_SET_EXTENSION.Length); - int.TryParse(fileNameIndex, out indexOfFile); - dateString = dateString.Substring(0, indexPos); - } - if (!dateStrings.Contains(dateString)) - { - dateStrings.Add(dateString); - DateTime date = DateTime.ParseExact(dateString, "dd-MM-yyyy_HH-mm-ss", CultureInfo.InvariantCulture); - logFiles.Add(new LogFile() { DateTime = date, File = file, PartOfSet = indexOfFile > 0, }); - } + DateTime date = DateTime.ParseExact(dateString, "dd-MM-yyyy_HH-mm-ss", CultureInfo.InvariantCulture); + logFiles.Add(new LogFile() { DateTime = date, File = file }); } catch (Exception ex) { @@ -50,71 +40,36 @@ namespace Tango.Logging public List<LogItemBase> Parse(LogFile logFile) { List<LogItemBase> logItems = new List<LogItemBase>(); - List<LogFile> logFiles = new List<LogFile>(); - FileLogger logger = LogManager.Default.RegisteredLoggers.FirstOrDefault(x => x.GetType() == typeof(FileLogger)) as FileLogger; - if (logFile.PartOfSet) - { - string fileName = Path.GetFileNameWithoutExtension(logFile.File); - string extension = Path.GetExtension(logFile.File); - int indexPos = fileName.IndexOf(FileLogger.FILE_SET_EXTENSION); - if (indexPos > 0) - { - fileName = fileName.Substring(0, indexPos); - } - string[] fileEntries = Directory.GetFiles(FileLogger.DefaultLogsFolder, $"{fileName}*{extension}").Where(x => Path.GetFileName(x).StartsWith(logger.Tag) && x != logger.LogFile).OrderBy(x => x).ToArray(); - foreach (var file in fileEntries) - { - Parse(file, logFile.DateTime, ref logItems); - } - } - else - { - Parse(logFile.File, logFile.DateTime, ref logItems); - } - return logItems; - } - - public List<LogItemBase> Parse(String file, DateTime fileDate) - { - List<LogItemBase> logs = new List<LogItemBase>(); - Parse(file, fileDate, ref logs); - return logs; - } + String text = File.ReadAllText(logFile.File); + var logs = Regex.Split(text, @"(\[\d{2}:\d{2}:\d{2}.\d{2}\])"); - private void Parse(string file, DateTime datetime, ref List<LogItemBase> logItems) - { - if(File.Exists(file)) + for (int i = 1; i < logs.Length; i += 2) { - String text = File.ReadAllText(file); - var logs = Regex.Split(text, @"(\[\d{2}:\d{2}:\d{2}.\d{2}\])"); - - for (int i = 1; i < logs.Length; i += 2) + try { - try - { - DateTime date = DateTime.ParseExact(logs[i].Replace("[", "").Replace("]", ""), "HH:mm:ss.ff", CultureInfo.InvariantCulture); - String rest = logs[i + 1]; + DateTime date = DateTime.ParseExact(logs[i].Replace("[", "").Replace("]", ""), "HH:mm:ss.ff", CultureInfo.InvariantCulture); + String rest = logs[i + 1]; - var matches = Regex.Matches(rest, @"(?<=\[)(.*?)(?=\])"); + var entries = Regex.Split(rest, @"\[(.*?)\]"); - MessageLogItem item = new MessageLogItem(); - item.TimeStamp = new DateTime(datetime.Year, datetime.Month, datetime.Day, date.Hour, date.Minute, date.Second, date.Millisecond); - item.Category = (LogCategory)Enum.Parse(typeof(LogCategory), matches[0].ToString()); - item.CallerFile = matches[1].ToString(); - item.CallerMethodName = matches[2].ToString(); - item.CallerLineNumber = int.Parse(matches[3].ToString()); + MessageLogItem item = new MessageLogItem(); + item.TimeStamp = new DateTime(logFile.DateTime.Year, logFile.DateTime.Month, logFile.DateTime.Day, date.Hour, date.Minute, date.Second, date.Millisecond); + item.Category = (LogCategory)Enum.Parse(typeof(LogCategory), entries[1]); + item.CallerFile = entries[3]; + item.CallerMethodName = entries[5]; + item.CallerLineNumber = int.Parse(entries[7]); + item.Message = new String(entries[8].Skip(2).ToArray()); - int messageStartIndex = matches[3].Index + matches[3].Length + 2; - item.Message = rest.Substring(messageStartIndex, rest.Length - messageStartIndex); - logItems.Add(item); - } - catch (Exception ex) - { - LogManager.Default.Log(ex, "Could not parse log line: " + logs[i]); - } + logItems.Add(item); + } + catch (Exception ex) + { + LogManager.Default.Log(ex, "Could not parse log line: " + logs[i]); } } + + return logItems; } } } diff --git a/Software/Visual_Studio/Tango.Logging/ExceptionLogItem.cs b/Software/Visual_Studio/Tango.Logging/ExceptionLogItem.cs index dab06455c..7c325ee19 100644 --- a/Software/Visual_Studio/Tango.Logging/ExceptionLogItem.cs +++ b/Software/Visual_Studio/Tango.Logging/ExceptionLogItem.cs @@ -13,28 +13,50 @@ namespace Tango.Logging [Serializable] public class ExceptionLogItem : LogItemBase { - private bool _messageSet; - - [NonSerialized] - private Exception _exception; /// <summary> /// Gets or sets the log item exception. /// </summary> - public Exception Exception - { - get { return _exception; } - set { _exception = value; } - } + public Exception Exception { get; set; } /// <summary> - /// Gets the log message. + /// Gets or sets the error description. /// </summary> - public override string Message { get; set; } + public String Description { get; set; } /// <summary> - /// Gets or sets the error description. + /// Gets the log message. /// </summary> - public String Description { get; set; } + public override string Message + { + get + { + if (Exception is AggregateException) + { + try + { + String message = String.Empty; + + if (Description != null) + { + message += Description + Environment.NewLine; + } + + message += String.Join(Environment.NewLine, (Exception as AggregateException).InnerExceptions.Select(x => x.Message)); + + return message; + } + catch + { + return Exception.Message; + } + } + else + { + return Exception.Message; + } + } + set { } + } /// <summary> /// Returns a formatted string of the log item. @@ -43,5 +65,6 @@ namespace Tango.Logging { return String.Format("[{0}] [{6}] [{1}] [{2}] [{3}]: {4}{5}", TimeStamp.ToString("HH:mm:ss.ff"), GetRelativeCallerFilePath(), CallerMethodName, CallerLineNumber, Description, Environment.NewLine + Exception.FlattenException(), Category); } + } } diff --git a/Software/Visual_Studio/Tango.Logging/FileLogger.cs b/Software/Visual_Studio/Tango.Logging/FileLogger.cs index 3c3ae970d..121ef5374 100644 --- a/Software/Visual_Studio/Tango.Logging/FileLogger.cs +++ b/Software/Visual_Studio/Tango.Logging/FileLogger.cs @@ -4,10 +4,7 @@ using System.Diagnostics; using System.IO; using System.Linq; using System.Text; -using System.Text.RegularExpressions; -using System.Threading; using System.Threading.Tasks; -using System.Windows.Threading; namespace Tango.Logging { @@ -17,18 +14,7 @@ namespace Tango.Logging /// <seealso cref="Tango.Logging.ILogger" /> public class FileLogger : ILogger { - private DateTime _logFileTimeDate; - private System.Timers.Timer _removal_timer; - private int _writeCount; - private int _fileExtensionIndex; - private const int FILE_SIZE_CHECK_COUNT = 100; - public const string FILE_SET_EXTENSION = "__"; - private Regex _passwordRegEx; - - /// <summary> - /// Gets or sets a value indicating whether to automatically locate password inside log messages and hide them. - /// </summary> - public bool ProtectPasswords { get; set; } + private DateTime _logFileDate; /// <summary> /// Gets the logs folder. @@ -51,49 +37,6 @@ namespace Tango.Logging public String Folder { get; private set; } /// <summary> - /// Gets or sets a value indicating whether [enable automatic log removal]. - /// </summary> - public bool EnableAutoLogRemoval { get; set; } - - /// <summary> - /// Gets or sets the automatic log removal period. - /// </summary> - public TimeSpan AutoLogRemovalPeriod { get; set; } - - private TimeSpan _autoLogRemovalCheckPeriod; - /// <summary> - /// Gets or sets the automatic log removal check period. - /// </summary> - public TimeSpan AutoLogRemovalCheckPeriod - { - get { return _autoLogRemovalCheckPeriod; } - set - { - _autoLogRemovalCheckPeriod = value; - - if (_removal_timer != null) - { - _removal_timer.Interval = _autoLogRemovalCheckPeriod.TotalMilliseconds; - } - } - } - - /// <summary> - /// Gets or sets a value indicating whether [enable maximum file size limit]. - /// </summary> - public bool EnableMaxFileSizeLimit { get; set; } - - /// <summary> - /// Gets or sets the maximum file size limit. - /// </summary> - public long MaxFileSizeLimit { get; set; } - - public String GetFileSetExtension(int index) - { - return FILE_SET_EXTENSION + index; - } - - /// <summary> /// Initializes the <see cref="FileLogger"/> class. /// </summary> static FileLogger() @@ -104,40 +47,28 @@ namespace Tango.Logging /// <summary> /// Initializes a new instance of the <see cref="FileLogger"/> class. /// </summary> - /// <param name="folder">Logs folder path.</param> - /// <param name="tag">The tag name which will be appended to the file name.</param> - public FileLogger(String folder, String tag) + public FileLogger() { _isEnabled = true; - Tag = tag; - Folder = folder; + Tag = Path.GetFileNameWithoutExtension(AppDomain.CurrentDomain.FriendlyName); + Folder = DefaultLogsFolder; Directory.CreateDirectory(Folder); - _logFileTimeDate = DateTime.Now; LogFile = CreateLogFileName(); - - EnableAutoLogRemoval = false; - AutoLogRemovalCheckPeriod = TimeSpan.FromHours(1); - AutoLogRemovalPeriod = TimeSpan.FromDays(7); - - _removal_timer = new System.Timers.Timer(); - _removal_timer.Interval = AutoLogRemovalCheckPeriod.TotalMilliseconds; - _removal_timer.Elapsed += _removal_timer_Elapsed; - _removal_timer.Start(); - - EnableMaxFileSizeLimit = true; - MaxFileSizeLimit = 1000000 * 10; - _fileExtensionIndex = 0; - - _passwordRegEx = new Regex("(\"(|.+)password\":)(|\\s)(\"[^,\"]+\")", RegexOptions.IgnoreCase); } /// <summary> /// Initializes a new instance of the <see cref="FileLogger"/> class. /// </summary> - public FileLogger() : this(DefaultLogsFolder, Path.GetFileNameWithoutExtension(AppDomain.CurrentDomain.FriendlyName)) + /// <param name="folder">Logs folder path.</param> + /// <param name="tag">The tag name which will be appended to the file name.</param> + public FileLogger(String folder, String tag) + : this() { - + Folder = folder; + Tag = tag; + Directory.CreateDirectory(Folder); + LogFile = CreateLogFileName(); } /// <summary> @@ -148,42 +79,14 @@ namespace Tango.Logging { try { - if (DateTime.Now.Date > _logFileTimeDate.Date) - { - _fileExtensionIndex = 0; - _writeCount = 0; - _logFileTimeDate = DateTime.Now; - CreateNewLogFile(); - } - else if (EnableMaxFileSizeLimit && ++_writeCount > FILE_SIZE_CHECK_COUNT) - { - if (new FileInfo(LogFile).Length > MaxFileSizeLimit) - { - if (_fileExtensionIndex == 0) - { - _fileExtensionIndex = 1; - string oldPath = LogFile; - LogFile = CreateLogFileName(); - File.Move(oldPath, LogFile); - } - _fileExtensionIndex++; - CreateNewLogFile(); - _writeCount = 0; - } - } - - String logString = output.ToString(); - - if (ProtectPasswords) + if (DateTime.Now.Date > _logFileDate.Date) { - try - { - logString = _passwordRegEx.Replace(logString, x => $"{x.Groups[1].Value}{x.Groups[3].Value}\"{new String('*', x.Groups[4].Length)}\""); - } - catch { } + File.AppendAllText(LogFile, Environment.NewLine + Environment.NewLine + "### This log file continues on the next log file ###" + Environment.NewLine); + LogFile = CreateLogFileName(); + File.AppendAllText(LogFile, "### This log file is a continuation of a previous log file ###" + Environment.NewLine + Environment.NewLine); } - File.AppendAllText(LogFile, logString + Environment.NewLine); + File.AppendAllText(LogFile, output.ToString() + Environment.NewLine); } catch { @@ -213,66 +116,8 @@ namespace Tango.Logging /// <returns></returns> private String CreateLogFileName() { - return Path.Combine(Folder, string.Format("{1}-{0:dd-MM-yyyy_HH-mm-ss}{2}.log", _logFileTimeDate, Tag, EnableMaxFileSizeLimit && _fileExtensionIndex > 0 ? GetFileSetExtension(_fileExtensionIndex) : String.Empty)); - } - - private void CreateNewLogFile() - { - File.AppendAllText(LogFile, Environment.NewLine + Environment.NewLine + "### This log file continues on the next log file ###" + Environment.NewLine); - LogFile = CreateLogFileName(); - File.AppendAllText(LogFile, "### This log file is a continuation of a previous log file ###" + Environment.NewLine + Environment.NewLine); + _logFileDate = DateTime.Now.Date; + return Path.Combine(Folder, string.Format("{1}-{0:dd-MM-yyyy_HH-mm-ss}.log", DateTime.Now, Tag)); } - - #region Auto Log Removal - - /// <summary> - /// Handles the Elapsed event of the _removal_timer control. - /// </summary> - /// <param name="sender">The source of the event.</param> - /// <param name="e">The <see cref="System.Timers.ElapsedEventArgs"/> instance containing the event data.</param> - private void _removal_timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) - { - if (EnableAutoLogRemoval) - { - RemoveOldLogFiles(); - } - } - - /// <summary> - /// Removes the old files. - /// </summary> - public void RemoveOldLogFiles() - { - try - { - if (Directory.Exists(Folder)) - { - DateTime removalDateTime = DateTime.Now - AutoLogRemovalPeriod; - string[] fileEntries = Directory.GetFiles(Folder, "*.log"); - foreach (string fileName in fileEntries) - { - try - { - FileInfo fi = new FileInfo(fileName); - - if (fi != null && fi.LastWriteTime < removalDateTime) - { - File.Delete(fi.FullName); - } - } - catch (Exception ex) - { - Debug.WriteLine(ex); - } - } - } - } - catch (Exception ex) - { - Debug.WriteLine(ex); - } - } - - #endregion } } diff --git a/Software/Visual_Studio/Tango.Logging/GlobalExceptionTrapper.cs b/Software/Visual_Studio/Tango.Logging/GlobalExceptionTrapper.cs index 3409ffdc4..5ee714cb6 100644 --- a/Software/Visual_Studio/Tango.Logging/GlobalExceptionTrapper.cs +++ b/Software/Visual_Studio/Tango.Logging/GlobalExceptionTrapper.cs @@ -1,12 +1,7 @@ using System; using System.Collections.Generic; -using System.Diagnostics; -using System.IO; using System.Linq; -using System.Reflection; -using System.Runtime.ExceptionServices; using System.Text; -using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows; using System.Windows.Threading; @@ -21,7 +16,6 @@ namespace Tango.Logging public class WpfGlobalExceptionTrapper : IGlobalExceptionTrapper { private DateTime _lastGlobalExceptionTime = DateTime.Now.AddMinutes(-1); - private Application _app; /// <summary> /// Occurs when the global exception trapper has detected an unhandled exception. @@ -34,7 +28,6 @@ namespace Tango.Logging /// <param name="app">The application.</param> public void Initialize(Application app) { - _app = app; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; app.Dispatcher.UnhandledException += Dispatcher_UnhandledException; Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException; @@ -42,17 +35,6 @@ namespace Tango.Logging } /// <summary> - /// Use only when need to simulate application crash! - /// </summary> - public void Disable() - { - AppDomain.CurrentDomain.UnhandledException -= CurrentDomain_UnhandledException; - _app.Dispatcher.UnhandledException -= Dispatcher_UnhandledException; - Application.Current.DispatcherUnhandledException -= Current_DispatcherUnhandledException; - TaskScheduler.UnobservedTaskException -= TaskScheduler_UnobservedTaskException; - } - - /// <summary> /// Handles the UnobservedTaskException event of the TaskScheduler control. /// </summary> /// <param name="sender">The source of the event.</param> @@ -101,58 +83,25 @@ namespace Tango.Logging { if (DateTime.Now < _lastGlobalExceptionTime.AddSeconds(1)) { + LogManager.Default.Log(exception, LogCategory.Critical); _lastGlobalExceptionTime = DateTime.Now; return true; } _lastGlobalExceptionTime = DateTime.Now; + LogManager.Default.Log("Application Crashed", LogCategory.Critical); + LogManager.Default.Log(exception, LogCategory.Critical); ApplicationCrashedEventArgs e = new ApplicationCrashedEventArgs(exception); ApplicationCrashed?.Invoke(this, e); - return e.TryRecover; - } - - public Task<MessageLogItem> GetLastApplicationCrashEventLog(int maxMinutes = 10) - { - return Task.Factory.StartNew<MessageLogItem>(() => + if (e.TryRecover) { - MessageLogItem logItem = null; - - try - { - var applicationEvents = new EventLog("Application"); - var events = applicationEvents.Entries.Cast<EventLogEntry>().Where(x => x.EntryType == EventLogEntryType.Error && x.Source == ".NET Runtime" && x.TimeWritten > DateTime.Now.AddMinutes(-maxMinutes)).OrderByDescending(x => x.TimeWritten).ToList(); - - Regex reg = new Regex("Application: (.+)"); - - foreach (var ev in events) - { - Match match = reg.Match(ev.Message); - if (match.Groups.Count > 1) - { - String exeName = match.Groups[1].Value; - String assemblyName = Path.GetFileNameWithoutExtension(exeName); - - if (assemblyName == Assembly.GetEntryAssembly().GetName().Name) - { - logItem = new MessageLogItem(); - logItem.Message = "Application terminated unexpectedly in the previous run!\n"; - logItem.Message += "This crash report was retrieved from the windows event logs.\n"; - logItem.Message += "---------------------------------------------------------------------------\n\n"; - logItem.Message += ev.Message; - logItem.TimeStamp = DateTime.Now; - logItem.Category = LogCategory.Critical; - break; - } - } - } - } - catch { } + LogManager.Default.Log("Trying application recovery. Ignoring exception..."); + } - return logItem; - }); + return e.TryRecover; } } } diff --git a/Software/Visual_Studio/Tango.Logging/ILogFileParser.cs b/Software/Visual_Studio/Tango.Logging/ILogFileParser.cs index 64b4c7206..bc43c7cd0 100644 --- a/Software/Visual_Studio/Tango.Logging/ILogFileParser.cs +++ b/Software/Visual_Studio/Tango.Logging/ILogFileParser.cs @@ -10,8 +10,6 @@ namespace Tango.Logging { List<T> Parse(LogFile logFile); - List<T> Parse(String file, DateTime fileDate); - List<LogFile> GetLogFiles(); } } diff --git a/Software/Visual_Studio/Tango.Logging/LogFile.cs b/Software/Visual_Studio/Tango.Logging/LogFile.cs index f727b96f4..66988b7ed 100644 --- a/Software/Visual_Studio/Tango.Logging/LogFile.cs +++ b/Software/Visual_Studio/Tango.Logging/LogFile.cs @@ -8,34 +8,8 @@ namespace Tango.Logging { public class LogFile { - /// <summary> - /// Gets or sets the date time started Log file. - /// </summary> public DateTime DateTime { get; set; } - /// <summary> - /// Gets or sets the full path of file. - /// </summary> public String File { get; set; } - - /// <summary> - /// Gets or sets the name of the file. - /// </summary> - public String FileName { get; set; } - - /// <summary> - /// Gets or sets a value indicating whether set of files - /// </summary> - public bool PartOfSet { get; set; } - - /// <summary> - /// Gets or sets the start index of the set. - /// </summary> - public int SetStartIndex { get; set; } - - /// <summary> - /// Gets or sets the set count of set. - /// </summary> - public int SetCount { get; set; } } } diff --git a/Software/Visual_Studio/Tango.Logging/LogItemBase.cs b/Software/Visual_Studio/Tango.Logging/LogItemBase.cs index d5271d213..f89b73b40 100644 --- a/Software/Visual_Studio/Tango.Logging/LogItemBase.cs +++ b/Software/Visual_Studio/Tango.Logging/LogItemBase.cs @@ -1,5 +1,4 @@ -using Newtonsoft.Json; -using System; +using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; @@ -23,10 +22,8 @@ namespace Tango.Logging /// <summary> /// Gets or sets an optional log object. /// </summary> - [JsonIgnore] public Object LogObject { - get { return _logObject; } set { _logObject = value; } } @@ -44,21 +41,12 @@ namespace Tango.Logging /// <summary> /// Gets the relative caller file. /// </summary> - [JsonIgnore] public String RelativeCallerFile { get { return GetRelativeCallerFilePath(); } } /// <summary> - /// Gets the name of the caller file class. - /// </summary> - public String ClassName - { - get { return RelativeCallerFile.Split('\\').LastOrDefault()?.Split('.').FirstOrDefault(); } - } - - /// <summary> /// Gets or sets the caller line number. /// </summary> public int CallerLineNumber { get; set; } diff --git a/Software/Visual_Studio/Tango.Logging/LogManager.cs b/Software/Visual_Studio/Tango.Logging/LogManager.cs index ba73b32b4..98bcaaa28 100644 --- a/Software/Visual_Studio/Tango.Logging/LogManager.cs +++ b/Software/Visual_Studio/Tango.Logging/LogManager.cs @@ -124,7 +124,6 @@ namespace Tango.Logging log.Exception = e; log.Category = category; log.Description = description; - log.Message = log.Description + Environment.NewLine + log.Exception.FlattenException(); AppendLog(log); @@ -132,6 +131,25 @@ namespace Tango.Logging } /// <summary> + /// Add new exception log item. + /// </summary> + /// <param name="e">Exception.</param> + /// <param name="description">Error description.</param> + public Exception LogFormat(Exception e, String description, object argument, [CallerMemberName] string caller = null, [CallerFilePath] string file = null, [CallerLineNumber] int lineNumber = 0) + { + return Log(e, LogCategory.Error, String.Format(description, argument), caller, file, lineNumber); + } + + /// <summary> + /// Add new message log item. + /// </summary> + /// <param name="message">Message.</param> + public String LogFormat(String message, object argument, [CallerMemberName] string caller = null, [CallerFilePath] string file = null, [CallerLineNumber] int lineNumber = 0) + { + return Log(String.Format(message, argument), LogCategory.Info, null, caller, file, lineNumber); + } + + /// <summary> /// Add new message log item. /// </summary> /// <param name="message">Message.</param> @@ -187,24 +205,20 @@ namespace Tango.Logging { String log = "--------------------- Referenced Assemblies --------------------------" + Environment.NewLine + Environment.NewLine; - try - { - string codeBase = typeof(LogManager).Assembly.CodeBase; - UriBuilder uri = new UriBuilder(codeBase); - string path = Uri.UnescapeDataString(uri.Path); - String folder = Path.GetDirectoryName(path); + string codeBase = typeof(LogManager).Assembly.CodeBase; + UriBuilder uri = new UriBuilder(codeBase); + string path = Uri.UnescapeDataString(uri.Path); + String folder = Path.GetDirectoryName(path); - foreach (var file in Directory.GetFiles(folder, "*.dll")) - { - FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(file); - string version = fvi.ProductVersion; - log += Path.GetFileNameWithoutExtension(file) + ", v" + version + Environment.NewLine; - } + foreach (var file in Directory.GetFiles(folder, "*.dll")) + { + FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(file); + string version = fvi.ProductVersion; + log += Path.GetFileNameWithoutExtension(file) + ", v" + version + Environment.NewLine; + } - log += Environment.NewLine + "--------------------- --------------------- --------------------------"; + log += Environment.NewLine + "--------------------- --------------------- --------------------------"; - } - catch { } Log(log); } @@ -257,14 +271,5 @@ namespace Tango.Logging NewLog?.Invoke(this, log); } } - - /// <summary> - /// Creates a new log safe which can be used to keep logs and then be disposed. - /// </summary> - /// <returns></returns> - public LogSafe CreateLogSafe() - { - return new LogSafe(this); - } } } diff --git a/Software/Visual_Studio/Tango.Logging/LogSafe.cs b/Software/Visual_Studio/Tango.Logging/LogSafe.cs deleted file mode 100644 index 2da51e90c..000000000 --- a/Software/Visual_Studio/Tango.Logging/LogSafe.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Tango.Logging -{ - public class LogSafe : IDisposable - { - private LogManager _logManager; - private List<LogItemBase> Logs { get; set; } - - public LogSafe(LogManager logManager) - { - _logManager = logManager; - Logs = new List<LogItemBase>(); - logManager.NewLog += LogManager_NewLog; - } - - private void LogManager_NewLog(object sender, LogItemBase log) - { - Logs.Add(log); - } - - public List<LogItemBase> EmptyAndDispose() - { - var list = Logs.ToList(); - Dispose(); - return list; - } - - public void Dispose() - { - _logManager.NewLog -= LogManager_NewLog; - Logs.Clear(); - } - } -} diff --git a/Software/Visual_Studio/Tango.Logging/SessionFileLogger.cs b/Software/Visual_Studio/Tango.Logging/SessionFileLogger.cs deleted file mode 100644 index 4e378bfbf..000000000 --- a/Software/Visual_Studio/Tango.Logging/SessionFileLogger.cs +++ /dev/null @@ -1,167 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Tango.Logging -{ - public class SessionFileLogger : ILogger - { - private bool _inInSession; - private int _writeCount; - private const string FILE_SESSION_EXTENSION = "_session"; - private const int FILE_SIZE_CHECK_COUNT = 100; - - #region Static Properties - - /// <summary> - /// Gets the default logs folder. - /// </summary> - public static String DefaultLogsFolder { get; private set; } - - #endregion - - #region Properties - - public bool Enabled { get; set; } - - /// <summary> - /// Folder is used for save file session logs - /// </summary> - public String Folder { get; private set; } - - /// <summary> - /// Full path of log file - /// </summary> - public String LogFile { get; private set; } - - /// <summary> - /// Gets the tag name which will be appended to the file. - /// </summary> - public String Tag { get; private set; } - - /// <summary> - /// Gets or sets the maximum file size limit. - /// </summary> - public long MaxFileSizeLimit { get; set; } - - #endregion - - #region Constructors - /// <summary> - /// Initializes the static members of the class. - /// </summary> - static SessionFileLogger() - { - DefaultLogsFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Twine", "Tango", "Logs", Path.GetFileNameWithoutExtension(AppDomain.CurrentDomain.FriendlyName), "Session"); - - } - - public SessionFileLogger(String folder, String tag) - { - Folder = folder; - Tag = tag; - Directory.CreateDirectory(Folder); - Enabled = true; - _writeCount = 0; - MaxFileSizeLimit = 1000000 * 10; //10 MB - } - - public SessionFileLogger() : this(DefaultLogsFolder, Path.GetFileNameWithoutExtension(AppDomain.CurrentDomain.FriendlyName)) - { - } - #endregion - - #region Public Methods - - /// <summary> - /// Creates the session. Only one file should be for session log, so removed old file and create a new file. - /// </summary> - public void CreateSession() - { - _writeCount = 0; - RemoveOldLogFile(); - LogFile = CreateLogFileName(); - _inInSession = true; - } - - /// <summary> - /// Ends the session. Set flag _inInSession to false. - /// </summary> - public void EndSession() - { - _inInSession = false; - } - - /// <summary> - /// Called when write to session log file. - /// </summary> - /// <param name="output">The output.</param> - public void OnLog(LogItemBase output) - { - if (_inInSession) - { - try - { - if (!File.Exists(LogFile) || (++_writeCount > FILE_SIZE_CHECK_COUNT && new FileInfo(LogFile).Length > MaxFileSizeLimit)) - { - CreateSession(); - } - - File.AppendAllText(LogFile, output.ToString() + Environment.NewLine); - } - catch (Exception ex) - { - Debug.WriteLine($"Error Writing To Session Log File!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n{ex.ToString()}"); - } - } - } - - #endregion - - #region Private Methods - - /// <summary> - /// Creates the name of the log file. - /// </summary> - /// <returns></returns> - private String CreateLogFileName() - { - return Path.Combine(Folder, string.Format("{1}-{0:dd-MM-yyyy_HH-mm-ss}{2}.log", DateTime.Now, Tag, FILE_SESSION_EXTENSION)); - } - - /// <summary> - /// Delete the old log file if is existed. - /// </summary> - private void RemoveOldLogFile() - { - try - { - if (Directory.Exists(Folder)) - { - string[] fileEntries = Directory.GetFiles(Folder, "*.log"); - foreach (string fileName in fileEntries) - { - try - { - File.Delete(fileName); - } - catch (Exception ex) - { - Debug.WriteLine(ex); - } - } - } - } - catch (Exception ex) - { - Debug.WriteLine(ex); - } - } - - #endregion - } -} diff --git a/Software/Visual_Studio/Tango.Logging/Tango.Logging.csproj b/Software/Visual_Studio/Tango.Logging/Tango.Logging.csproj index 549113657..311579625 100644 --- a/Software/Visual_Studio/Tango.Logging/Tango.Logging.csproj +++ b/Software/Visual_Studio/Tango.Logging/Tango.Logging.csproj @@ -31,9 +31,6 @@ <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> - <Reference Include="Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL"> - <HintPath>..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll</HintPath> - </Reference> <Reference Include="PresentationCore" /> <Reference Include="PresentationFramework" /> <Reference Include="System" /> @@ -66,14 +63,12 @@ <Compile Include="LogCategory.cs" /> <Compile Include="LogItemBase.cs" /> <Compile Include="LogManager.cs" /> - <Compile Include="LogSafe.cs" /> <Compile Include="MessageLogItem.cs" /> <Compile Include="ApplicationLogFileParser.cs" /> <Compile Include="ILogFileParser.cs" /> <Compile Include="LogFile.cs" /> <Compile Include="ProducerConsumerQueue.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> - <Compile Include="SessionFileLogger.cs" /> <Compile Include="SimpleStringLogger.cs" /> <Compile Include="VSOutputLogger.cs" /> </ItemGroup> @@ -83,9 +78,6 @@ <Generator>MSBuild:Compile</Generator> </Page> </ItemGroup> - <ItemGroup> - <None Include="packages.config" /> - </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <ProjectExtensions> <VisualStudio> diff --git a/Software/Visual_Studio/Tango.Logging/packages.config b/Software/Visual_Studio/Tango.Logging/packages.config deleted file mode 100644 index 7ee8c1052..000000000 --- a/Software/Visual_Studio/Tango.Logging/packages.config +++ /dev/null @@ -1,4 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<packages> - <package id="Newtonsoft.Json" version="9.0.1" targetFramework="net461" /> -</packages>
\ No newline at end of file |
