2

log4netアプリケーションに別のイベントログを使用するように設定しました。イベントログが存在し、表示されます(以前は機能していたログにログを記録します!)

名前は"sbsysrst" isUatですtrue

予想されるLogNameはSB3-UATですが、以下のデバッグメッセージにもかかわらず、アプリケーションログのログ記録を要求します。log4net

ILogオブジェクトを返すメソッド。

public static ILog GetLogger(string name, bool isUat = false)
{
    var eventLogAppender = new EventLogAppender
    {
        ApplicationName = name,
        Layout = new PatternLayout
        {
            ConversionPattern = "%message%newline%exception" 
        },
        LogName = "SB3" + (isUat ? "-" + UatSuffix : string.Empty),
        Threshold = Level.Info
    };

    BasicConfigurator.Configure(eventLogAppender, FileAppenders[isUat]);
    eventLogAppender.ActivateOptions();
    return LogManager.GetLogger(name);
}

log4netからのデバッグ出力

log4net: Searched for existing files in [C:\Windows\...]
log4net: curSizeRollBackups starts at [0]
log4net: Opening file for writing [C:\Windows\...\SB3.log] append [True]
log4net: Searched for existing files in [C:\Windows\...]
log4net: curSizeRollBackups starts at [0]
log4net: Opening file for writing [C:\Windows\...\SB3.log] append [True]
log4net: Searched for existing files in [C:\Windows\...UAT]
log4net: curSizeRollBackups starts at [0]
log4net: Opening file for writing [C:\Windows\...UAT\SB3.log] append [True]
log4net: Searched for existing files in [C:\Windows\...UAT]
log4net: curSizeRollBackups starts at [0]
log4net: Opening file for writing [C:\Windows\...UAT\SB3.log] append [True]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: log4net assembly [log4net, Version=1.2.11.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a]. Loaded from [...]. (.NET Runtime [2.0.50727.5448] on Microsoft Windows NT 6.1.7601 Service Pack 1)
log4net: defaultRepositoryType [log4net.Repository.Hierarchy.Hierarchy]
log4net: Creating repository for assembly [..., Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]
log4net: Assembly [..., Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] Loaded From [...]
log4net: Assembly [..., Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] does not have a RepositoryAttribute specified.
log4net: Assembly [..., Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] using repository [log4net-default-repository] and repository type [log4net.Repository.Hierarchy.Hierarchy]
log4net: log4net assembly [log4net, Version=1.2.11.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a]. Loaded from [...]. (.NET Runtime [2.0.50727.5448] on Microsoft Windows NT 6.1.7601 Service Pack 1)
log4net: defaultRepositoryType [log4net.Repository.Hierarchy.Hierarchy]
log4net: Creating repository for assembly [..., Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]
log4net: Assembly [..., Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] Loaded From [...]
log4net: Assembly [..., Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] does not have a RepositoryAttribute specified.
log4net: Assembly [..., Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] using repository [log4net-default-repository] and repository type [log4net.Repository.Hierarchy.Hierarchy]
log4nlog4net: Creating repository [log4net-default-repository] using type [log4net.Repository.Hierarchy.Hierarchy]
et: Creating repository [log4net-default-repository] using type [log4net.Repository.Hierarchy.Hierarchy]
log4net: Changing event source [sbsysrst] from log [SB3] to log [SB3-UAT]
log4net: Source [sbsysrst] is registered to log [SB3-UAT]
log4net: Changing event source [sbsysrst] from log [SB3] to log [SB3-UAT]
log4net: Source [sbsysrst] is registered to log [SB3-UAT]

アップデート1

log4netのソースコードを見ると、コードは主にfollowimgに要約されます。

// Inside ActivateOptions()
using (SecurityContext.Impersonate(this))
{
    sourceAlreadyExists = EventLog.SourceExists(m_applicationName);
    if (sourceAlreadyExists)
    {
        currentLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName);
    }
}

using (SecurityContext.Impersonate(this))
{
    if (sourceAlreadyExists && currentLogName != m_logName)
    {
        //
        // Re-register this to the current application if the user has changed
        // the application / logfile association
        //
        EventLog.DeleteEventSource(m_applicationName, m_machineName);
        CreateEventSource(m_applicationName, m_logName, m_machineName);

        registeredLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName);
    }
    else if (!sourceAlreadyExists)
    {
        CreateEventSource(m_applicationName, m_logName, m_machineName);

        registeredLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName);
    }
}

// Inside Append(LoggingEvent loggingEvent)
using(SecurityContext.Impersonate(this))
{
    EventLog.WriteEntry(m_applicationName, eventTxt, entryType, eventID, category);
}

重要な部分は、期待どおりにSB3-UATEventLog.LogNameFromSourceName(m_applicationName, m_machineName);を返すことです。

アップデート2

ログとソース名に設定されたEventLogAppenderインスタンスオブジェクトを使用して、log4net機能をオーバーライドする独自の機能を作成しました。Eventlog

どちらも機能しなかった私の非常に驚いたことに、私はますますマシンの問題、またはのSecurityContext.Impersonate()コードと関係があることに傾いていますlog4net

アップデート3

したがって、これはlog4netの問題ではなく、dotnetの問題でもありません。以下は、Windows APIを直接使用するコードですが、それでも失敗します。ソース名がアプリケーションログに登録されたことがあるという事実は、物事をつまずかせています。

この混乱を解消できるかどうかを確認するために、適切なWinAPIを調べています。確かにレジストリキーを見ると、これは問題にはならないはずです。

const string SourceName = "sbsysrst";
const string TextMessage = "Test";
const string MachineName = ".";

// This code is essentially the watered down version behind `EventLog`
// in dotnet.  There are two main WinAPI calls and just boiler code around
// passing parameters to them as expected.

var message = new[] { TextMessage };
SafeHandle eventLogHandle = null;
var numArray = new IntPtr[message.Length];
var gcHandleArray = new GCHandle[mesage.Length];
GCHandle gcHandle = GCHandle.Alloc(numArray, GCHandleType.Pinned);
try
{
    eventLogHandle = SafeEventLogWriteHandle
        .RegisterEventSource(MachineName, SourceName);
    for (int index = 0; index < message.Length; index++)
    {
        gcHandleArray[index] = GCHandle
            .Alloc(message[index], GCHandleType.Pinned);
        numArray[index] = gcHandleArray[index]
            .AddrOfPinnedObject();
    }

    if (!ReportEvent(
        eventLogHandle,
        0x0004,           // Information type
        0,                // Category
        0,                // EventID
        null,             // user id
        message.Length,   // size of text array
        0,                // size of raw data array
        new HandleRef(this, gcHandle.AddrOfPinnedObject()),
        new byte[0]))     // raw data (none)
    {
        throw new Win32Exception(Marshal.GetLastWin32Error());
    }

}
finally
{
    for (int index = 0; index < message.Length; ++index)
    {
        if (gcHandleArray[index].IsAllocated)
        {
            gcHandleArray[index].Free();
        }
    }

    gcHandle.Free();
    if (eventLogHandle != null)
    {
        eventLogHandle.Dispose();
    }
}

// RegisterEventSource cannot return an abstract object.
internal sealed class SafeEventLogWriteHandle :
    SafeHandleZeroOrMinusOneIsInvalid
{
    internal SafeEventLogWriteHandle() : base(true)
    {
    }

    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    internal static extern SafeEventLogWriteHandle RegisterEventSource(
        string uncServerName, string sourceName);

    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
    [DllImport("advapi32.dll", SetLastError = true)]
    private static extern bool DeregisterEventSource(IntPtr hEventLog);

    protected override bool ReleaseHandle()
    {
        return DeregisterEventSource(this.handle);
    }
}
4

1 に答える 1

3

問題は、ソース名が過去に別のEventLogで登録されていたという事実にありました。ソース登録が(レジストリで)変更されている間、EventLogサービスが登録をキャッシュしているように見えます。マシンを再起動してもう一度ログに記録しようとすると(Eventlogサービスを再起動できません)、イベントエントリは正しいイベントログに入りました。

于 2012-11-26T10:15:26.460 に答える