So i have WPf
application and with Log4Net
so each time i want to add log
i just add it this way:
log4net.Info("bla bla");
In addition i want to add logger form
so i created another form
and from my main form
i opens it this way:
LoggerForm loggerForm = new LoggerForm();
loggerForm.Show();
And create Log object
:
public class LogEntry : PropertyChangedBase
{
public string DateTime { get; set; }
public int Index { get; set; }
public string Source{ get; set; }
public Level Level { get; set; }
public string Message { get; set; }
}
And LogHelper
that hold this LogEvent
objects inside List
and also add every LogEvent
into this List
:
public static class LogHelper
{
public static ObservableCollection<LogEntry> LogEntries { get; set; }
public static bool AddLogToList { get; set; }
private static int Index;
public static void AddLog(Level level, string message, string source)
{
if (AddLogToList)
{
Application.Current.Dispatcher.Invoke(new Action(() =>
{
if (LogEntries.Count == 1000)
LogEntries.RemoveAt(0);
LogEntry logEntry = new LogEntry()
{
DateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss,fff"),
Index = Index++,
Level = level,
Source = source,
Message = message.Trim()
};
LogEntries.Add(logEntry);
}));
}
}
}
And from my Logger form
after InitializeComponent
register into my list CollectionChanged
:
LogHelper.AddLogToList = true;
LogHelper.LogEntries.CollectionChanged += LogEntries_CollectionChanged;
This line:
LogHelper.AddLogToList = true;
Indicate that my Logger form
is opened so i can insert my LogEvent
iunto my List.
CollectionChanged:
Each time new LogEvent
added into my List
i update my ItemSource
into my ListView
:
ListView lvLogger;
private void LogEntries_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
lvLogger.ItemsSource = LogHelper.LogEntries;
}
Ok so those are my questions:
Each time i want to create new
Log
i type it twice:log.Info("bla bla"); LogHelper.AddLog(Level.Info, "bla bla", $"MyClassName\\MyMethodName");
So as you can see i use here string twice, so i wonder if this will better to use maybe
String.Builder
instead ofstring
?
I also want to mention that i update my log via different threads.
When my Logger
form
closed i register to its closingevent
and clear myLogEvent
list:private void MetroWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) { LogHelper.AddLogToList = false; LogHelper.LogEntries.Clear(); }
So my question here is should i unregistered here to my
LogEntries_CollectionChanged
event:LogHelper.LogEntries.CollectionChanged -= LogEntries_CollectionChanged;
Or this is redundant ?