在不确切知道您如何配置和使用 log4net 的情况下,很难编写适合您现有框架的代码:此示例创建了两个附加程序,一个使用%method
,一个使用%property{ExceptionMethod}
,并将它们分配给不同的记录器:
public abstract class BaseAppender : AdoNetAppender
{
protected BaseAppender()
{
// Add common parameters, set connection strings etc
// e.g.
this.AddParameter(new AdoNetAppenderParameter
{
ParameterName = "@log_level",
DbType = DbType.String,
Size = 50,
Layout = new RawLayoutConverter().ConvertFrom(new PatternLayout("%level")) as IRawLayout
});
// Then ask each subclass to add the extra parameters
this.AddExtraParameters();
}
protected abstract void AddExtraParameters();
}
public class RuntimeAppender : BaseAppender
{
protected override void AddExtraParameters()
{
this.AddParameter(new AdoNetAppenderParameter
{
ParameterName = "@Method",
DbType = DbType.String,
Size = 255,
Layout = new RawLayoutConverter().ConvertFrom(new PatternLayout("%method")) as IRawLayout
});
}
}
public class UnhandledExceptionAppender : BaseAppender
{
protected override void AddExtraParameters()
{
this.AddParameter(new AdoNetAppenderParameter
{
ParameterName = "@Method",
DbType = DbType.String,
Size = 255,
Layout =
new RawLayoutConverter().ConvertFrom(new PatternLayout("%property{ExceptionMethod}")) as IRawLayout
});
}
}
public sealed class RuntimeLogger : Logger
{
public RuntimeLogger(string name)
: base(name)
{
this.Appenders.Add(new RuntimeAppender());
this.Level = Level.Error; // etc
}
}
public sealed class UnhandledExceptionLogger : Logger
{
public UnhandledExceptionLogger(string name)
: base(name)
{
this.Appenders.Add(new UnhandledExceptionAppender());
this.Level = Level.Error; // etc
}
}
然后,在运行时,您选择使用哪个:
public class ExceptionHandler
{
public void HandleException(Exception ex)
{
string exceptionMethod = "set exception method here" ;
GlobalContext.Properties["ExceptionMethod"] = exceptionMethod;
var logger = new UnhandledExceptionLogger("Logger Name Goes Here");
logger.Log(Level.Error, "Message", ex);
}
}
public class RuntimeLogging
{
public void LogSomething(Exception ex)
{
var logger = new RuntimeLogger("Logger Name Goes Here");
logger.Log(Level.Error, "Message", ex);
}
}