Log4Net не может найти %username свойство, когда я называю файл в своем appender

Вы бы использовали архиватор Maven:

<plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-jar-plugin</artifactId>
      <configuration>
        <archive>
          <manifest>
            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
          </manifest>
        </archive>
      </configuration>
    </plugin>
  </plugins>

Это добавит следующее в файл манифеста:

Implementation-Title: ${pom.name}
Implementation-Version: ${pom.version}
Implementation-Vendor-Id: ${pom.groupId}
Implementation-Vendor: ${pom.organization.name}
5
задан Anthony Mastrean 16 June 2011 в 03:51
поделиться

1 ответ

Using the environment variable pattern works for me:

<file type="log4net.Util.PatternString" value="Logs\\%env{USERNAME}.txt" />

Update: if the USERNAME environment variable is not an option, subclassing PatternString could be an alternative. Here is a simple implementation:

public class MyPatternString : PatternString
{
    public MyPatternString()
    {
        AddConverter("usernameonly", typeof(UserNameOnlyConverter));
    }    
}

public class UserNameOnlyConverter : PatternConverter 
{
    override protected void Convert(TextWriter writer, object state) 
    {
        var windowsIdentity = WindowsIdentity.GetCurrent();
        if (windowsIdentity != null && windowsIdentity.Name != null)
        {
            var name = windowsIdentity.Name.Split('\\')[1];
            writer.Write(name);
        }
    }
}

The new setting will look like this:

<file type="MyPatternString" value="Logs\\%usernameonly.txt" />

Update 2: to answer why %identity and %property{user} doesn't work:

The %identity pattern picks up the identity property on the current thread. This property is in my tests null, and is probably so until one assigns a specific Windows identity to the running thread. This will not work in the context of the appender because you will not know which thread will perform the actual appending.

The %property pattern picks up properties from the GlobalContext and ThreadContext classes. By default, only the log4net:HostName (LoggingEvent.HostNameProperty) is registered in the GlobalContext. So unless you actively register properties in those contexts you cannot use them with the %property pattern. Again, ThreadContext is useless in the context of the appender since you have no way of knowing which thread will be doing the appending.

That said, registering a property called username in the GlobalContext.Properties collection, somewhere in the application startup routine perhaps, will enable the %property{username} to work as expected.

10
ответ дан 18 December 2019 в 11:58
поделиться
Другие вопросы по тегам:

Похожие вопросы: