Question

Trying to add logging to an application using Log4Net.

It's possible I have wholly misunderstood what this framework is for and how it works, but what I'd like to do is have a custom facade class, under which I actually spin up my log4net instance and which (and here's the trouble) uses a single config file by default, which can be overridden by applications using the class if necessary.

So I've created a custom Log4NetLogger class and an interface for it:

public class Log4NetLogger : ILogging
{
     private ILog _logger;

     public Log4NetLogger()
     {
         log4net.Config.XmlConfigurator.Configure();
        _logger = LogManager.GetLogger(this.GetType());
        string meh = string.Empty;
     }

    //interface methods for error, warn, info etc
 }

In my AssemblyInfo.cs for the project containing my Log4NetLogger class I have added:

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

And to the project I've added a Log4Net.config file which looks a bit like this:

<log4net>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
<!-- various gubbins -->
<root>
  <level value="ALL" />
  <appender-ref ref="AdoNetAppender" />
</root>
</log4net>

And which is set to "copy always" when compiled, so there should be a copy of it in the bin folder of any project that references it.

Now, in a test class I've added a reference to this project and done this:

        Log4NetLogger logger = new Log4NetLogger();
        logger.Info("started");

Which does absolutely nothing.

Stepping through the code in the debugger it becomes apparent that Log4Net is not picking up the config file. The logger sent back by the log manager has all the levels turned to disabled.

If you add the same config sections to the web.config of my test project, however, it works. But I really don't want to have to add enormous quantities of identical appender configuration in each and every config file in the solution.

What am I doing wrong, is there anything wrong with my approach, and what's the best way forward?

Cheers, Matt

Was it helpful?

Solution

You should be able to remove the attributes entries from AssemblyInfo.cs and change your constructor to pass in the file name.

public Log4NetLogger()
{
    log4net.Config.XmlConfigurator.ConfigureAndWatch(
       new System.IO.FileInfo("Log4Net.config"));      

    _logger = LogManager.GetLogger(this.GetType());
    string meh = string.Empty;
 }

OTHER TIPS

You need to have an appender section where you configure where the logging is saved. you can refer to this link as well Log4net does not write the log file

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top