dll文件下载:http://logging.apache.org/log4net/download_log4net.cgi
配置文件:
<?xml version="1.0"?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/> </configSections> <log4net> <root> <level value="ALL"/> <appender-ref ref="rollingFile"/> <appender-ref ref="ColoredConsoleAppender"/> </root> <appender name="rollingFile" type="log4net.Appender.RollingFileAppender,log4net"> <param name="File" value="log.txt"/> <param name="AppendToFile" value="false"/> <param name="RollingStyle" value="Date"/> <param name="DatePattern" value="yyyy.MM.dd"/> <param name="StaticLogFileName" value="true"/> <layout type="log4net.Layout.PatternLayout,log4net"> <param name="ConversionPattern" value="%date [%thread] (%file:%line) %-5level %logger [%property{NDC}] - %message%newline"/> </layout> </appender> <appender name="consoleApp" type="log4net.Appender.ConsoleAppender,log4net"> <layout type="log4net.Layout.PatternLayout,log4net"> <param name="ConversionPattern" value="%date [%thread] (%file:%line) %-5level %logger [%property{NDC}] - %message%newline"/> </layout> </appender> <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender"> <mapping> <level value="ERROR" /> <foreColor value="White" /> <backColor value="Red, HighIntensity" /> </mapping> <mapping> <level value="WARN" /> <backColor value="Yellow" /> </mapping> <mapping> <level value="DEBUG" /> <backColor value="Green" /> </mapping> <mapping> <level value="INFO" /> <backColor value="Blue" /> </mapping> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] (%file:%line) %-5level %logger [%property{NDC}] - %message%newline" /> </layout> </appender> </log4net> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> </configuration>
AssemblyInfo.cs 中添加: [assembly: log4net.Config.XmlConfigurator(Watch = true)]
程序中使用log4net:
using System; using log4net; namespace Demo01 { class Program { private static readonly ILog Log = LogManager.GetLogger(typeof(Program)); static void Main(string[] args) { //记录严重错误 Log.Fatal("fatal", new Exception("发生了一个致命错误")); //记录错误日志 Log.Error("error", new Exception("发生了一个异常")); //记录警告信息 Log.Warn("warn"); //记录调试信息 Log.Debug("debug"); //记录一般信息 Log.Info("info"); Console.WriteLine("日志记录完毕。"); Console.Read(); } } }
运行结果: