log4net Configuration for console app
Asked Answered
A

2

10

can anyone suggest how to configure the log4net for an console app?

Or at least how/where to catch the Application_Start event? (It seams that some calls are required at this moment)

Thanks in advance!

Amador answered 16/11, 2009 at 13:3 Comment(0)
F
10

You need to configure it before the first logger is instantiated.

To do so:

  • Your main class (Program.cs) should not have a logger

  • The main method should not reference any classes that have a logger.

  • You can then configure log4net in the main method.

Alternatively you can use a wrapper class to instantiate loggers, that ensures log4net is configured before creating a logger, e.g.:

static class Log4NetHelper
{
    private static bool _isConfigured;

    static void EnsureConfigured()
    {
        if (!_isConfigured)
        {
            ... configure log4net here ...
            _isConfigured = true;
        }
    }

    public static ILog GetLogger(string name)
    {
        EnsureConfigured();
        log4net.ILog logger = log4net.LogManager.GetLogger(name);
        return logger;
    }
}
Fowkes answered 16/11, 2009 at 13:15 Comment(0)
L
13

Try writing

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

in AssemblyInfo.cs

That's it!

Lent answered 18/11, 2009 at 7:12 Comment(3)
What is this supposed to do ? I doesn't seem to help anything in my case.Utah
It is supposed to 1) tell log4net to configure itself using the default settings (app.config) 2) cause log4net to auto-reload it's configuration when the underlying file that contains the log4net entry changes.Sapiential
@Tomas you also need to add the log4net config to the app.config fileMarginate
F
10

You need to configure it before the first logger is instantiated.

To do so:

  • Your main class (Program.cs) should not have a logger

  • The main method should not reference any classes that have a logger.

  • You can then configure log4net in the main method.

Alternatively you can use a wrapper class to instantiate loggers, that ensures log4net is configured before creating a logger, e.g.:

static class Log4NetHelper
{
    private static bool _isConfigured;

    static void EnsureConfigured()
    {
        if (!_isConfigured)
        {
            ... configure log4net here ...
            _isConfigured = true;
        }
    }

    public static ILog GetLogger(string name)
    {
        EnsureConfigured();
        log4net.ILog logger = log4net.LogManager.GetLogger(name);
        return logger;
    }
}
Fowkes answered 16/11, 2009 at 13:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.