Log4Net section in Web.Config generates Error

≡放荡痞女 提交于 2019-11-29 13:32:31

Take a look at a sample configurations at log4net documentation homepage.
Chances are you've misplaced required tags.

Mubashar

For developers who are not sure exactly how to get started following might be a help

ConfigSections in app.config

Remember to tell your application that a library is introducing a custom configuration section are you are intended to utilize, I am not perfectly sure if it is mandatory or not but I always use it as first section within root <configuration> tag.

<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>

log4net config in app.config

There are quite a variety of different appenders available in log4net but I usually use RollingFileAppender so I am using the same one in this sample, you can find rest of those here.

<log4net>
    <!-- file appender -->
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="C:/logs/my_log_file.log"/>
      <appendToFile value="true"/>
      <rollingStyle value="Date"/>
      <maxSizeRollBackups value="30"/>
      <datePattern value=".yyyy-MM-dd"/>
      <staticLogFileName value="true"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
      </layout>
    </appender>
    <root>
      <level value="DEBUG"/>
      <appender-ref ref="RollingFileAppender"/>
    </root>
  </log4net>

Update AssemblyInfo.cs file

I always miss this step whenever I have to create a new project. So remember you have to tell your application to watch for XMLConfigurator to perform configuration of log4net, so following line goes at the end of AssemblyInfo.cs file:

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

Get Started

Remember to include the reference of log4net.dll then use following line of code to initialize logger within a class

private static ILog log = LogManager.GetLogger(typeof(MyClass));

And at the end lets use it like following

log.Info("Hello log4net");

Happy Logging :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!