i have 2 appender in web config ,first one save logs in xml file , and another save logs using external API , my issue is :
i need to set my default appender is to call external API just , no need to save on xml file , and if api reutred failed , i want to use logging by xml file ( i did it at run time).
main question : how to set first appender is default for logging in web.config file
web.config :
<log4net>
<!--workflow logging-->
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
<param name="File" value="C:/Workspaces/workflowLog/workflow-info.xml" />
<param name="AppendToFile" value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="Tahaluf.Workflow.Common.Core.Log.WorkFlowXmlLayout" />
</appender>
<!--Connect to Tahaluf Logging-->
<appender name="WorkFlowAppender" type="Tahaluf.Workflow.Common.Core.Log.WorkFlowAppender">
</appender>
<root>
<level value="ALL" />
<appender-ref ref="WorkFlowAppender" />
<appender-ref ref="LogFileAppender" />
</root>
</log4net>
The solution is to modify the Threshold
of the appender.
web.config:
<root>
<level value="ALL" />
<appender-ref ref="WorkFlowAppender" />
<appender-ref ref="LogFileAppender" />
</root>
Add method:
public static void SetThreshold(string appenderName, log4net.Core.Level threshold)
{
foreach (log4net.Appender.AppenderSkeleton appender in log4net.LogManager.GetRepository().GetAppenders())
{
if (appender.Name == appenderName)
{
appender.Threshold = threshold;
break;
}
}
}
Turn appender off: SetThreshold("LogFileAppender", log4net.Core.Level.Off);
Turn appender on: SetThreshold("LogFileAppender", log4net.Core.Level.Debug);
Level can be any valid level (not only Debug
)
Only set your default appender in your web.config. You want to use the
WorkFlowAppender
, so remove the LogFileAppender
.
<root>
<level value="ALL"/>
<appender-ref ref="WorkFlowAppender"/>
</root>
If you need to use your LogFileAppender
later, you add it by code.
// Add an appender to a logger
public void AddAppender(string loggerName,
log4net.Appender.IAppender appender)
{
log4net.ILog log = log4net.LogManager.GetLogger(loggerName);
log4net.Repository.Hierarchy.Logger l =
(log4net.Repository.Hierarchy.Logger)log.Logger;
l.AddAppender(appender);
}
// Find a named appender already attached to a logger
public log4net.Appender.IAppender FindAppender(string
appenderName)
{
foreach (log4net.Appender.IAppender appender in
log4net.LogManager.GetRepository().GetAppenders())
{
if (appender.Name == appenderName)
{
return appender;
}
}
return null;
}
Take a look at this post, too.
Edit
This solution doesn't work when the appender-ref of LogFileAppender
is not set.