Log4net 控制台打印日志(二)
1.创建控制台程序
2.用NuGet添加log4net引用
3.添加应用程序配置文件:App.config
4.添加配置信息:
1 <?xml version="1.0" encoding="utf-8" ?> 2 <configuration> 3 <configSections> 4 <!--添加配置节点--> 5 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> 6 </configSections> 7 8 <log4net> 9 <!--日志保存到文件里面 txt--> 10 <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender"> 11 <mapping> 12 <level value="ERROR" /> 13 <foreColor value="White" /> 14 <backColor value="Red,HighIntensity" /> 15 </mapping> 16 17 <mapping> 18 <level value="DEBUG" /> 19 <backColor value="Green" /> 20 </mapping> 21 22 <mapping> 23 <level value="Info" /> 24 <backColor value="Yellow" /> 25 </mapping> 26 27 <layout type="log4net.Layout.PatternLayout"> 28 <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /> 29 </layout> 30 31 <filter type="log4net.Filter.LevelRangeFilter"> 32 <param name="LevelMin" value="Debug"/> 33 <param name="LevelMax" value="Fatal"/> 34 </filter> 35 36 </appender> 37 <root> 38 <!--配置可输出日志级别--> 39 <level value="all"/> 40 <!--应用配置--> 41 <appender-ref ref="ColoredConsoleAppender"/> 42 </root> 43 </log4net> 44 45 </configuration>
5.程序中代码:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using log4net; 6 7 namespace 控制台输出日志 8 { 9 class Program 10 { 11 12 static void Main(string[] args) 13 { 14 //初始化log4net配置 15 log4net.Config.XmlConfigurator.Configure(); 16 ILog log = LogManager.GetLogger(typeof(Program)); 17 log.Info("普通日志"); 18 log.Error("错误日志"); 19 log.Debug("异常信息"); 20 log.Fatal("致命错误"); 21 log.Warn("警告信息"); 22 23 Console.ReadKey(); 24 } 25 } 26 }
6.展示: