标签:
首先需要下载并引用Log4net的binary。这一步可以通过在Visual Studio里的Manage Nuget package for solution轻松添加。
第二步是配置config文件,可以是App.config或Web.config或者单独的config文件:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <log4net> <root> <level value="ALL" /> <appender-ref ref="ConsoleAppender" /> <appender-ref ref="RollingFileAppender" /> </root> <logger name="default"> </logger> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date %-5level - %message%newline" /> </layout> </appender> <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="CrawlerLog.txt" /> <threshold value="WARN"/> <rollingStyle value="Size" /> <maxSizeRollBackups value="10" /> <maximumFileSize value="1MB" /> <staticLogFileName value="true" /> <layout type="log4net.Layout.PatternLayout"> <footer value="-------------------------------------------------------------" /> <conversionPattern value="%newline%-5level %date %newline%message%newline%exception" /> </layout> </appender> </log4net> </configuration>
第三步,需要告诉Log4net去哪里找这些配置,这一步可以通过在AssemblyInfo.cs里添加以下内容完成:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "<your exe name>.exe.config", ConfigFileExtension = "config", Watch = true)]
如果是web项目,可以在Global.asax里的Application_Start方法里添加一行:
log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(System.Web.HttpContext.Current.Server.MapPath("web.config")));
第四步,创建一个ILog实例,这样就可以开始使用了:
using System; using log4net; namespace MyConsoleApp { class Program { static ILog logger = log4net.LogManager.GetLogger("default"); static int Main(string[] args) { logger.Debug("debug msg"); logger.Info("info msg"); logger.Warn("warn msg"); logger.Error("error msg", new Exception("test exception")); Console.Read(); return 0; } } }
一些补充说明:
标签:
原文地址:http://www.cnblogs.com/polymorphism/p/Configure_Log4net.html