1. Add log4net. DLL to project reference
2. Modify assemblyinfo. CS and add the following lines:
[Assembly: log4net. config. xmlconfigurator (watch = true)] 3. modify the configuration file <? XML version = "1.0" encoding = "UTF-8"?>
<Configuration>
<Configsections>
<Section name = "log4net" type = "system. configuration. ignoresectionhandler"/>
</Configsections>
<Log4net>
<Appender name = "patternfileappender" type = "sampleappendersapp. appender. patternfileappender, sampleappendersapp">
<File value = "% Date {yyyy-mm-dd} \ % property {session} \ output. log"/>
<Layout type = "log4net. layout. patternlayout" value = "% date [% thread] %-5 level % logger [% NDC]-% message % newline"/>
</Appender>
<Root>
<Level value = "all"/>
<Appender-ref = "patternfileappender"/>
</Root>
</Log4net>
</Configuration> 4. The form1 code is as follows: using system;
Using system. Collections. Generic;
Using system. componentmodel;
Using system. Data;
Using system. drawing;
Using system. LINQ;
Using system. text;
Using system. Windows. forms;
Using system. Threading;
Using log4net. core;
Namespace winformdemo
{
Public partial class form1: Form
{
Private Static readonly log4net. ilog log = log4net. logmanager. getlogger (system. reflection. methodbase. getcurrentmethod (). declaringtype );
Private bool logwatching = true;
Private log4net. appender. memoryappender logger;
Private thread logwatcher;
Public form1 ()
{
Initializecomponent ();
This. Closing + = new canceleventhandler (form1_closing );
Logger = new log4net. appender. memoryappender ();
Log4net. config. basicconfigurator. Configure (logger );
Logwatcher = new thread (New threadstart (logwatcher ));
Logwatcher. Start ();
}
Void form1_closing (Object sender, canceleventargs E)
{
Logwatching = false;
Logwatcher. Join ();
}
Delegate void delonestr (string log );
Void appendlog (string _ log)
{
If (txtlog. invokerequired)
{
Delonestr dd = new delonestr (appendlog );
Txtlog. Invoke (DD, new object [] {_ log });
}
Else
{
Stringbuilder builder;
If (txtlog. lines. length> 99)
{
Builder = new stringbuilder (txtlog. Text );
Builder. Remove (0, txtlog. Text. indexof ('\ r', 3000) + 2 );
Builder. append (_ log );
Txtlog. Clear ();
Txtlog. appendtext (builder. tostring ());
}
Else
{
Txtlog. appendtext (_ log );
}
}
}
Private void logwatcher ()
{
While (logwatching)
{
Loggingevent [] events = logger. getevents ();
If (events! = NULL & events. length> 0)
{
Logger. Clear ();
Foreach (loggingevent EV in events)
{
String line = eV. loggername + ":" + eV. renderedmessage + "\ r \ n ";
Appendlog (line );
}
}
Thread. Sleep (500 );
}
}
Private void timereffectick (Object sender, eventargs E)
{
Random r = new random ();
Int x = R. Next (1, 4 );
Switch (X)
{
Case 1:
Log. Info ("Notification: Notification ");
Break;
Case 2:
Log. Warn ("Warning: Warning warning ");
Break;
Case 3:
Log. Error ("error: Error error ");
Break;
Case 4:
Log. Fatal ("severe: serious, serious ");
Break;
}
}
}
}