简体   繁体   中英

Best practices for creating a logger library using log4net. Is

My goal is to create a log4net library that can be shared across multiple projects.

In my solution which is in .net 4.0, I created a class library called Logger and referenced it from web project.

Now I created a logger.config in the class library and put all the configuration in the logger.config file. I then used

[assembly: log4net.Config.XmlConfigurator(Watch = true, ConfigFile = "Logger.config")]

When I run the web app nothing is getting logged. So I added this line of code in web.config

<add key="log4net.Internal.Debug" value="true"/> 

which gave me debugging info and error information

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:

I moved the configuration from logger.config to web.config and everything seems to work fine.

I don't want the log4net configuration in web.config but have it logger.config as a cleaner approach. The goal is to make other projects use this library and not have to worry about configuration in every project.

Now the question is, How do I do this? What am I doing wrong? Any suggestion with code example will be beneficial to everyone.

FYI, I am using structure map IOC to reslove the logger before logging to it.

I believe you are trying to reinvent the wheel, there are several tools to abstract the loggers from your code decoupling the logger framework from your code:

http://slf.codeplex.com/

http://netcommon.sourceforge.net/

Those are the most common in .Net applications.

Well now if you insist in using your own abstraction (which is valid), this is my suggestion:

First of all, I assume that you would have something like:

interface ILogger
{
    void Debug(string message);
    void Info(string message);
    void Warn(string message);
    …..
}

Ok so in your code you would inject a singleton reference of your logger, like:

x.For<ILogger>().Singleton().Use<MyLogger>();

Now, I usually prefer convention over configuration, but in the case of loggers, the configuration through a config file is a big advantage because when your code is in production, you will want sometimes to change the logging rules by disabling or enabling loggers, change the log-level, and enable/disable named loggers.

The easiest and most reusable way I have found to accomplish this is by placing the configuration in an external file as you commented, then I do not bother calling the XmlConfigurator in code, because it is simpler to me just add a couple of application settings to my config file like this

<!-- Relative to the application root path -->
<add key="log4net.Config" value="Logger.log4net"/>
<add key="log4net.Config.Watch" value="True"/>

That's it. Those application settings override your log4net configuration and they are easy to maintain. Your config file will look like:

<?xml version="1.0" encoding="utf-8" ?>

<!-- This section contains the log4net configuration settings -->
<log4net>

  <!-- Define some output appenders -->

  <appender name="LogFileAppender" type="log4net.Appender.FileAppender" >
    <file value="webapp-log.txt" />
    <appendToFile value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline" />
    </layout>
  </appender>

  <!-- Setup the root category, add the appenders and set the default priority -->

  <root>
    <level value="DEBUG" />
    <appender-ref ref="LogFileAppender" />
  </root>

</log4net>

To configure more appenders: click here

In your projects you only need a reference to your logger abstraction component, and just in the web project (or windows application, it's the same) add the log4net config file and just those application settings

Since you are creating a reusable component I would recommend you to setup an internal Nuget server in your organization (it's just an IIS application) and use it to deploy your components, in this case the library containing the logger. Also it would be better if you create a different Nuget package containing only the application settings and the log4net configuration file, so you can install this Nuget package only in your web project

Maybe for your web application, you can try to load the configuration file in your application_start (gloabal.asax.cs)

    void Application_Start(object sender, EventArgs e)
    {
        log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(Server.MapPath("Logger.config")));
    }

You may want to try this : http://forums.asp.net/t/1739162.aspx/1 or this one . The web application will look only to it's main webconfig and configs from areas/folder if you have, by default. You should make sure you include all the required configs like below in you new appConfig for log4net :

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

  <log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="logfile.txt"/>
      <appendToFile value="true"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] – %message%newline"/>
      </layout>
    </appender>
    <root>
      <level value="DEBUG"/>
      <appender-ref ref="FileAppender"/>
    </root>
  </log4net>

ps check this answer too : Can a web.config read from an external xml file? Make sure you deploy the config file too, if the web.config doesn't include it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM