一、概述
log4net获取日志输出并显示到界面上
二、使用
public void GetLogMessage()
{
var appender = log4net.Appender.MemoryAppender;
if (appender == null)
{
return;
}
while (true)
{
try
{
var level = log4net.Core.Level.All;
if (appender.Threshold != level)
{
appender.Threshold = level;
}
var list = appender.PopAllEvents();
var sb = new StringBuilder();
foreach (var item in list)
{
sb.AppendFormat("{1}【{0:yyyy-MM-dd HH:mm:ss.fff}】 {2}", item.TimeStamp, item.Level, item.RenderedMessage);
sb.AppendLine();
if (item.ExceptionObject != null)
{
sb.AppendLine(item.GetExceptionString());
}
}
if (sb.Length > 0)
{
this.Dispatcher.Invoke(() =>
{
try
{
if (tb_LogMsg.Text.Length > 1024 * 1024)
{
tb_LogMsg.Text = tb_LogMsg.Text.Substring(tb_LogMsg.Text.Length - 1024 * 512);
}
tb_LogMsg.AppendText(sb.ToString());
tb_LogMsg.ScrollToVerticalOffset(double.MaxValue);
}
catch (Exception ex)
{
m_log.Error("更新日志信息到界面出错", ex);
}
});
}
}
catch (Exception ex)
{
m_log.Error("刷新日志信息出错", ex);
}
Thread.Sleep(1000);
}
}