这边先介绍简单的使用:在控制台输出和写入文件
首先添加log4net的nuget包
然后在app.config中添加配置项==configSections只能有一个,且是configuration的首个节点
<?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.2" /> </startup> <log4net> <root> <level value="WARN" /> <appender-ref ref="LogFileAppender" /> <appender-ref ref="ConsoleAppender" /> </root> <logger name="testApp.Logging"> <level value="DEBUG"/> </logger> <appender name="LogFileAppender" type="log4net.Appender.FileAppender" > <param name="File" value="log_file.txt" /> <!--<param name="File" value="D:/log_file.txt" />--> <param name="AppendToFile" value="true" /> <layout type="log4net.Layout.PatternLayout"> <!--<param name="Header" value="[Header] "/> <param name="Footer" value="[Footer] "/>--> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="DEBUG" /> <param name="LevelMax" value="WARN" /> </filter> </appender> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" > <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" /> </layout> </appender> </log4net> </configuration>
这部分代码也可以单独放在一个配置文件中,起名log4net.config,我们把这个文件和app.config放在同一层
接着在AssemblyInfo.cs下添加特性
//配置文件在app.config中 [assembly: log4net.Config.XmlConfigurator(Watch = true)] //配置文件在log4net.config中 //[assembly: log4net.Config.XmlConfigurator(ConfigFile="log4net.config", Watch = true)]
Watch=true监视配置文件,当配置文件发生变化的时候,就会重新加载。
static void Main(string[] args) { log4net.ILog log = log4net.LogManager.GetLogger("testApp.Logging");//获取一个日志记录器 //配置文件在app.config中 log4net.Config.XmlConfigurator.Configure(); //配置文件在log4net.config中 //string assemblyFilePath = Assembly.GetExecutingAssembly().Location; //string assemblyDirPath = Path.GetDirectoryName(assemblyFilePath); //DirectoryInfo pathInfo = new DirectoryInfo(assemblyDirPath); //string configFilePath = pathInfo.Parent.Parent.FullName + "//log4net.config"; //log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(configFilePath)); //绝对路径 //log4net.Config.XmlConfigurator.Configure(newSystem.IO.FileInfo(@"E:/DEMO/Log4NetDemo/emoTest/log4net.config")); Thread.CurrentThread.Name = "main"; log.Debug("初始化连接开始"); log.Warn("测试"); log.Info(DateTime.Now.ToString() + ": login success"); Console.ReadKey(); }
到此这篇关于C# log4net使用案例详解的文章就介绍到这了,更多相关Java log4net使用内容请搜索自学编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持自学编程网!
- 本文固定链接: https://zxbcw.cn/post/219643/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)