Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Log4Net新事件日志不工作_C#_Winapi_Log4net - Fatal编程技术网

C# Log4Net新事件日志不工作

C# Log4Net新事件日志不工作,c#,winapi,log4net,C#,Winapi,Log4net,我已设置log4net为我的应用程序使用单独的事件日志。 事件日志存在且可见(记录到该日志甚至可以正常工作!) 名称为“sbsysrst”isUatistrue 预期的日志名为SB3-UAT,但尽管下面有log4net调试消息,它仍坚持记录到应用程序日志 方法返回ILog对象 public static ILog GetLogger(string name, bool isUat = false) { var eventLogAppender = new EventLogAppender

我已设置
log4net
为我的应用程序使用单独的事件日志。 事件日志存在且可见(记录到该日志甚至可以正常工作!)

名称为“sbsysrst”
isUat
is
true

预期的日志名为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源代码,代码主要归结为以下代码:

// 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);
}
关键部分是
EventLog.LogNameFromSourceName(m_applicationName,m_machineName)返回的SB3-UAT与预期一致

更新2

我已经编写了自己的
EventLogAppender
,它通过使用设置为日志和源名称的实例
Eventlog
对象来覆盖log4net功能

令我大吃一惊的是,这也不起作用,所以我越来越倾向于机器问题,或者是与
SecurityContext.Impersonate()有关的问题

更新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);
    }
}
const string SourceName=“sbsysrst”;
常量字符串TextMessage=“测试”;
常量字符串MachineName=“.”;
//这段代码本质上是`EventLog后面的淡化版本`
//在dotnet中。这里有两个主要的WinAPI调用,只有锅炉代码
//按预期向它们传递参数。
var message=new[]{TextMessage};
SafeHandle eventLogHandle=null;
var numArray=newintptr[message.Length];
var gcHandleArray=新的GCHandle[mesage.Length];
GCHandle GCHandle=GCHandle.Alloc(numArray,GCHandleType.pinted);
尝试
{
eventLogHandle=SafeEventLogWriteHandle
.RegisterEventSource(MachineName,SourceName);
for(int index=0;index
问题在于源名称在过去注册在不同的事件日志中。虽然源注册已更改(在注册表中),但似乎EventLog服务会缓存注册。重新启动计算机并再次尝试登录时(您无法重新启动Eventlog服务),事件条目进入正确的Eventlog。

谢谢!我也对这种行为感到震惊。