【发布时间】:2018-03-27 08:19:20
【问题描述】:
所以我有WPf 应用程序和Log4Net所以每次我想添加log 我只是这样添加:
log4net.Info("bla bla");
此外,我想添加记录器form,所以我创建了另一个form,并从我的主form 以这种方式打开它:
LoggerForm loggerForm = new LoggerForm();
loggerForm.Show();
并创建日志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; }
}
而LogHelper 将这个LogEvent 对象保存在List 中,并将每个LogEvent 添加到这个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);
}));
}
}
}
然后从我的记录器formInitializeComponent 注册到我的列表CollectionChanged:
LogHelper.AddLogToList = true;
LogHelper.LogEntries.CollectionChanged += LogEntries_CollectionChanged;
这一行:
LogHelper.AddLogToList = true;
表示我的 Logger form 已打开,因此我可以将我的 LogEvent 插入到我的列表中。
CollectionChanged:
每次将新的LogEvent 添加到我的List 时,我都会将我的ItemSource 更新为我的ListView:
ListView lvLogger;
private void LogEntries_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
lvLogger.ItemsSource = LogHelper.LogEntries;
}
好的,这些是我的问题:
-
每次我想创建新的
Log我都会输入两次:log.Info("bla bla"); LogHelper.AddLog(Level.Info, "bla bla", $"MyClassName\\MyMethodName");所以你可以看到我在这里使用了两次字符串,所以我想知道这是否会更好地使用
String.Builder而不是string?
我还想提一下,我通过不同的线程更新我的日志。
-
当我的 Logger
form关闭时,我注册到它的关闭event并清除我的LogEvent列表:private void MetroWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) { LogHelper.AddLogToList = false; LogHelper.LogEntries.Clear(); }所以我的问题是我应该在这里取消注册我的
LogEntries_CollectionChanged事件:LogHelper.LogEntries.CollectionChanged -= LogEntries_CollectionChanged;
或者这是多余的?
【问题讨论】:
标签: wpf multithreading log4net