最近想学习下log4net,写了个很简短的使用例子。用少的代码,可以保证程序运行起来。
配置文件:
<configSections> <section name="log4net" type="System.Configuration.IgnoreSectionHandler" /> </configSections> <log4net> <appender name="LogFileAppender" type="log4net.Appender.FileAppender"> <file value="../log.txt" /> <layout type="log4net.Layout.PatternLayout"> <footer value="[Footer]--Test By Ring1981 " /> <conversionPattern value="%date [%thread] %-5level %logger [%ndc] <%property{auth}> - %message%newline" /> </layout> </appender> <root> <appender-ref ref="LogFileAppender" /> </root> </log4net>
代码:
public class Program { static void Main(string[] args) { LogTest a = new LogTest(); a.TestMethod(); Console.ReadLine(); } } public class LogCOM { public static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); } public class LogTest { public string TestMethod() { try { List<string> list = new List<string>(); list.Add("a"); list.Add("b"); list.Add("c"); list.Add("d"); string e = list.FirstOrDefault(x => x == "e"); e.ToString(); return "tet"; } catch (Exception ex) { LogCOM.log.Error("test",ex); return ""; } } }
写在命名空间上部。
[assembly: log4net.Config.XmlConfigurator(Watch = true)]