动态地设置一个appender文件路径的最佳方法

问题描述:

我试图找到一些比我聪明,以验证某些语法我写了。我们的想法是配置我的RollingFileAppender进行到装配的名称的文件名,以使其更可重复使用的为我的项目。

I am trying to find somebody smarter than me to validate some syntax I wrote up. The idea is to configure the filename of my RollingFileAppender to the name of the assembly in order to make it more re-usable for my projects.

我见过的this previous SO文章,但它并不完全能回答我的问题...

I've seen this previous SO article but it wasn't exactly able to answer my question...

我有一个时间试图了解的log4net的内部组件的狄更斯,这就是我想出了(居住在Global.asax文件 - Application_Start方法中):

I've had a dickens of a time trying to understand the inner components of Log4net and this is what I came up with (residing in the Global.asax file - Application_Start method):

// Bind to the root hierarchy of log4net
log4net.Repository.Hierarchy.Hierarchy root = 
  log4net.LogManager.GetRepository() 
    as log4net.Repository.Hierarchy.Hierarchy;

if (root != null)
{
  // Bind to the RollingFileAppender
  log4net.Appender.RollingFileAppender rfa = 
    (log4net.Appender.RollingFileAppender)root.Root.GetAppender("RollingLogFileAppender");

  if (rfa != null)
  {
    // Set the file name based on the assembly name
    string filePath = 
      string.Format("~/App_Data/{0}.log", GetType().Assembly.GetName().Name);

    // Assign the value to the appender
    rfa.File = Server.MapPath(filePath);

    // Apply changes to the appender
    rfa.ActivateOptions();
  }
}

谁能告诉我,这是可怕的,或这应该能正常运行?另外,如果我设置文件动态可我仍然期望log4net的行为的文件基础上,log4net.config文件设置旋转?

Can anyone tell me, 'this is hideous', or 'this should work fine'? Also, if I set the file dynamically can I still expect the log4net behavior to rotate the files based on the log4net.config file settings?

大部分AP preciated!

Much appreciated!

您在做这个硬盘的方式!定义你的log4net的配置为XML的应用程序的配置文件,并使用%产权{} 来的优势:

You are doing this the hard way! Define your log4net config as XML in your application's configuration file and use %property{} to advantage:

<appender name="YourAppender" type="log4net.Appender.RollingFileAppender">
  <file type="log4net.Util.PatternString" value="~/App_Data/%property{LogName}" />
  ....
</appender>

这是动态的 - 你只需要设置log4net的财产 LOGNAME 之前初始化log4net的。因此,在你的code任何时候,你log4net的配置之前,设置此属性的所需值:

This is dynamic -- you just have to set the log4net property "LogName" before you initialize log4net. Thus, in your code any time before you configure log4net, set the desired value of this property:

string LogName = GetType().Assembly.GetName().Name + ".log";
log4net.GlobalContext.Properties["LogName"] = LogName;

当然,你可以使用任何属性名。我选择LOGNAME一个简单的例子,但你可以有每个应用程序之一,如果你愿意,只要你的code知道正确的属性名称是什么,怎样才是正确的值应该是。

Of course, you may use any property name. I've chosen "LogName" for a simple example, but you can have one per application if you want, as long as your code knows what the correct property name is and what the correct value should be.