Log4Net section in Web.Config generates Error

后端 未结 2 1666
清歌不尽
清歌不尽 2020-12-19 02:25

So I am trying to set up Log4Net in my Web .NET 4.0 application. I have added the correct .dll to my project and have appended the following to my Web.Config file as starte

相关标签:
2条回答
  • 2020-12-19 03:15

    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 :)

    0 讨论(0)
  • 2020-12-19 03:21

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

    0 讨论(0)
提交回复
热议问题