前言
最近在使用log4net进行日志记录,保存一些需要的数据,以便后期使用需要。在使用的时候出现没有生成日志文件,针对这些问题,发现解决的办法!
遇到的问题
报错,提示没有找到对应的文件。
log4net:ERROR Failed to find configuration section ‘log4net’ in the application’s .config file. Check your .config file for the and elements. The configuration section should look like:
再看对应的log4net的log.Info(message);中的log内部都是false。
查了很多资料就是配置不对,读不到配置。
具体使用
- 项目中的App.config中要将对应的log4net配置写清楚
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<!-- 将日志以回滚文件的形式写到文件中 -->
<!-- 内部定义存储的形式 -->
<root>
<!-- 控制级别定义 -->
</root>
</log4net>
-
log4net.Config.XmlConfigurator.Configure();
的使用。
如果在AssemblyInfo.cs
中定义了[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4net.config", Watch = true)]
,那么上面的第一点其实需要写在Log4net.config
中,程序启动的时候去设置它;如果没有写这个,那么就需要在程序中使用log4net.Config.XmlConfigurator.Configure();
,同时需要在app.config
中启动。
也就是log4net.Config.XmlConfigurator.Configure();
与app.config
搭配;
或者AssemblyInfo.cs
与[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4net.config", Watch = true)]
搭配,再加Log4net.config
。 -
使用
log.Info("Info信息!" + DateTime.Today.ToString());
总结
总结了自己在使用log4net中间出现的问题,希望可以帮助大家!