Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add log4net appender in runtime?

Tags:

c#

.net

log4net

How do I add an extra log appender in runtime? (all pre-existing appenders must keep on working)
I'm trying it this way:

        var layout = new PatternLayout("%utcdate %-5level - %message%newline");
        layout.ActivateOptions();
        _log4netAppender = new FileAppender
            {
                Layout = layout,
                File = logFilePath,
            };
        _log4netAppender.ActivateOptions();
        BasicConfigurator.Configure(_log4netAppender);

but it doesn't write anything to the file.

like image 646
Steve Kero Avatar asked Nov 07 '13 10:11

Steve Kero


2 Answers

You should also add the appender to a logger. Take a look here Adding Appenders programmatically

If the logger you are using is, for example ILog logger do:

((log4net.Repository.Hierarchy.Logger)logger.Logger).AddAppender(appender)

like image 180
Salvatore Sorbello Avatar answered Oct 13 '22 19:10

Salvatore Sorbello


var patternLayout = new log4net.Layout.PatternLayout
{
    ConversionPattern = "%date %level %message%newline"
};
patternLayout.ActivateOptions();

var rollingFileAppender = new log4net.Appender.RollingFileAppender
{
    File = "MyApp.log",
    Layout = patternLayout
};
rollingFileAppender.ActivateOptions();

var hierarchy = (log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetRepository();
hierarchy.Root.AddAppender(rollingFileAppender);
hierarchy.Root.Level = log4net.Core.Level.All; // Default is Debug

log4net.Config.BasicConfigurator.Configure(hierarchy);
like image 4
Der_Meister Avatar answered Oct 13 '22 20:10

Der_Meister