在log4net中,我尝试使用以下代码以编程方式为每个实例添加附加器。
我会明白为什么要为RollingFileAppender
我写:
((Logger)log.Logger).AddAppender(newFileAppender);
在AdoNetAppenders
期间,我必须写:
hierarchy.Root.AddAppender(newAdoNetAppender);
如果我写:
hierarchy.Root.AddAppender(newFileAppender);
它将记录每行两次。
如果我写:
((Logger)log.Logger).AddAppender(newAdoNetAppender);
它不会登录数据库。
或者也许还有其他错误?
Global.asax :
XmlConfigurator.ConfigureAndWatch(new FileInfo("Foo.xml"));
属性定义:
LogicalThreadContext.Properties["InstanceName"] = instance;
代码:
public static void SetLog4NetAppenderOptions(ILog log, string instanceName)
{
Hierarchy hierarchy = LogManager.GetRepository() as Hierarchy;
if (hierarchy != null)
{
RollingFileAppender genericFileAppender = (RollingFileAppender)hierarchy.GetAppenders().FirstOrDefault(x => x.GetType() == typeof(RollingFileAppender) && x.Name == "RollingFile");
if (genericFileAppender != null)
{
genericFileAppender.Threshold = defaultLevel;
genericFileAppender.ActivateOptions();
if (!String.IsNullOrEmpty(instanceName))
{
RollingFileAppender specificFileAppender = (RollingFileAppender)hierarchy.GetAppenders().FirstOrDefault(x => x.GetType() == typeof(RollingFileAppender) && x.Name == "RollingFile_" + instanceName);
if (specificFileAppender == null)
{
RollingFileAppender newFileAppender = new RollingFileAppender();
newFileAppender.Threshold = defaultLevel;
newFileAppender.AppendToFile = genericFileAppender.AppendToFile;
newFileAppender.MaximumFileSize = genericFileAppender.MaximumFileSize;
newFileAppender.MaxFileSize = genericFileAppender.MaxFileSize;
newFileAppender.LockingModel = genericFileAppender.LockingModel;
newFileAppender.Layout = genericFileAppender.Layout;
newFileAppender.Name = String.Format("RollingFile_{0}", instanceName);
newFileAppender.File = genericFileAppender.File.Replace("_log", "_" + instanceName); newFileAppender.ActivateOptions(); ((Logger)log.Logger).AddAppender(newFileAppender);
}
}
}
if (!String.IsNullOrEmpty(instanceName))
{
AdoNetAppender specificDbAppender = (AdoNetAppender)hierarchy.GetAppenders().FirstOrDefault(x => x.GetType() == typeof(AdoNetAppender) && x.Name == "AdoNetAppender_" + instanceName);
if (specificDbAppender == null)
{
AdoNetAppender newAdoNetAppender = new AdoNetAppender();
newAdoNetAppender.ConnectionType = "Foo";
newAdoNetAppender.CommandText = "Foo";
newAdoNetAppender.Name = String.Format("AdoNetAppender_{0}", instanceName);
newAdoNetAppender.AddParameter(new AdoNetAppenderParameter
{
ParameterName = "@log_date",
DbType = DbType.DateTime,
Layout = new RawTimeStampLayout()
});
// add other parameters
newAdoNetAppender.ConnectionString = ConfigurationManager.ConnectionStrings[Settings.Default.ConnectionStringBaseKey + instanceName].ConnectionString;
newAdoNetAppender.ActivateOptions();
hierarchy.Root.AddAppender(newAdoNetAppender);
}
}
}
}
编辑: 如果我运行两次此代码,则必须添加一次,第二次它将忽略过滤器。
答案 0 :(得分:0)
最后我发现:
hierarchy.Root.AddAppender(newFileAppender);
是最好的解决方案,但只能使用MinimalLock,因此:
newFileAppender.LockingModel = new FileAppender.MinimalLock();