log4net真是个不错的库,在我最近写的程序中,如果没有UI,我几乎都会在程序中引入log4net。我们需要知道程序发生了什么。我通常将日志写入文本文件,如果要实时查看日志可以使用BareTail之类的软件打开日志文件。如果新的日志消息被加入文件,BareTail会将新的消息显示在列表中,而如果使用记事本之类的软件我们需要重新打开软件才能看到新的日志消息。
log4net提供了很多Appender,可以让我们将日志消息“附加”到各种“媒介”上——文本文件、数据库、UDP广播、内存……这次我利用MemoryAppender实现我需要的功能——将日志消息实时显示在Windows Form程序的TextBox控件中。
程序分为总共有两个Form,主Form上面有一个TextBox控件。
Form1代码:
using System;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Core;
namespace Log4NetScrollingTextbox
{
public partial class Form1 : Form
{
private static readonly ILog logger = LogManager.GetLogger(typeof (Form1));
private readonly MemoryAppender appender;
private readonly Thread logWatcher;
private bool logWatching = true;
public Form1()
{
InitializeComponent();
FormClosing += Form1_FormClosing;
appender = new MemoryAppender();
BasicConfigurator.Configure(appender);
logWatcher = new Thread(LogerWatch);
logWatcher.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
logWatching = false;
logWatcher.Join();
}
private void LogerWatch()
{
while (logWatching)
{
LoggingEvent[] events = appender.GetEvents();
if (events != null && events.Length > 0)
{
// if there are events, we clear them from the logger,
// since we're done with them
appender.Clear();
foreach (LoggingEvent ev in events)
{
string line = ev.LoggerName + ": " + ev.RenderedMessage + "\r\n";
AppendLog(line);
}
}
Thread.Sleep(500);
}
}
private void AppendLog(string line)
{
if (textBox1.InvokeRequired)
{
BeginInvoke(new Action<string>(DoAppendLog), line);
}
else
{
DoAppendLog(line);
}
}
private void DoAppendLog(string line)
{
if (textBox1.Lines.Length > 99)
{
var builder = new StringBuilder(textBox1.Text);
// strip out a nice chunk from the beginning
builder.Remove(0, textBox1.Text.IndexOf('\r', 3000) + 2);
builder.Append(line);
textBox1.Clear();
// using AppendText since that makes sure the TextBox stays
// scrolled at the bottom
textBox1.AppendText(builder.ToString());
}
else
{
textBox1.AppendText(line);
}
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval = 1000;
timer1.Enabled = true;
}
private void Timer1Tick(object sender, EventArgs e)
{
logger.Info(string.Format("现在时间是:{0}", DateTime.Now));
}
private void Button1Click(object sender, EventArgs e)
{
var form = new Form2();
form.Show();
}
}
}
Form2代码:
using System;
using System.Windows.Forms;
using log4net;
namespace Log4NetScrollingTextbox
{
public partial class Form2 : Form
{
public static readonly ILog logger = LogManager.GetLogger(typeof (Form2));
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
logger.Info("Form2 Opened.");
timer1.Interval = 1000;
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
logger.Info(string.Format("现在时间是:{0}", DateTime.Now));
}
}
}
将Log4Net的消息实时显示在Windows Form的TextBox控件中
最新推荐文章于 2025-04-02 23:30:00 发布