C# – logging to custom event log (C# app, but using win32 API)

cevent-logpinvoke

Due to a limitation in the .NET EventLog class, I have some code using PInvoke that logs to the Application log. The code works without a problem.

But now, I'd like to log to a custom event log. So, I tried changing the 2nd parameter of the RegisterEventSource to "companyX" (my custom log). It correctly wrote to "companyX" (instead of the Application log), but it also set the Source field (of the individual log entry) to "companyX," which is not what I want.

So how do I modify the code to:

  • Use the new, custom event log ("companyX"), but also
  • Use the correct Source value ("MyApp")

Currently, it either correctly writes to the Application log (with the correct Source value of "MyApp"), or it writes to the custom ("companyX") event log, and uses the incorrect Source value (rather than "MyApp", it sets the Source value to "companyX", the name of the custom log).

EDIT: Note that the "companyX" log has already been created (in WIX installer code).

Here's my code:

private void WriteEntryToLog(string msg, LogEventType entryType)
{
    // ApplicationName = "MyApp"
    // The code as-is is writing to the Application log. Changing the 2nd param of
    // the function below to "companyX" allows me to write to my "companyX" event log,
    // but also changes the Source value of each entry append to that log to "companyX" rather than "MyApp"
    IntPtr eventSrcHandle = NativeMethods.RegisterEventSource(null, Resources.ApplicationName);


    try
    {
        uint tokenInfoSize = 0;
        IntPtr userTokenPtr = WindowsIdentity.GetCurrent().Token;
        const UInt16 typeError = 1, typeWarning = 2, typeInformation = 4;

        //using this first call, get the length required to hold the token information in the tokenInfoSize parameter
        bool bresult = NativeMethods.GetTokenInformation(userTokenPtr, NativeMethods.TOKEN_INFORMATION_CLASS.TokenUser, IntPtr.Zero, tokenInfoSize, out tokenInfoSize);
        if (bresult) throw new Win32Exception(Marshal.GetLastWin32Error());

        IntPtr userTokenInfo = Marshal.AllocHGlobal((int)tokenInfoSize);
        try
        {
            //get the user token now with the pointer allocated to the right size
            bresult = NativeMethods.GetTokenInformation(userTokenPtr, NativeMethods.TOKEN_INFORMATION_CLASS.TokenUser, userTokenInfo, tokenInfoSize, out tokenInfoSize);
            if (!bresult) throw new Win32Exception(Marshal.GetLastWin32Error());

            UInt16 type = typeError;
            switch (entryType)
            {
                case LogEventType.Error:
                    type = typeError; 
                    break;
                case LogEventType.Warning:
                    type = typeWarning; 
                    break;
                case LogEventType.Information:
                    type = typeInformation; 
                    break;
                    default: 
                        type = typeInformation; 
                        break;
            }

            NativeMethods.TOKEN_USER tokUser = (NativeMethods.TOKEN_USER)Marshal.PtrToStructure(userTokenInfo, typeof(NativeMethods.TOKEN_USER));

            string[] message = new string[1];
            message[0] = msg;
            bresult = NativeMethods.ReportEvent(eventSrcHandle, type, 0, 0, tokUser.User.Sid, 1, 0, message, new byte());
            if (!bresult) throw new Win32Exception(Marshal.GetLastWin32Error());
        }
        finally
        {
            Marshal.FreeHGlobal(userTokenInfo);
        }
    }
    finally
    {
        NativeMethods.DeregisterEventSource(eventSrcHandle);
    }

}

Oh, and this is not a repeat of the question here:
Custom value for the Event Log source property for ASP.NET errors
since I have to use PInvoke for this. =)

Best Answer

You have to create a source called MyApp and map it to your log "CompanyX".

This article goes into detail for creating an Event Source w/ .Net Framework BCL.

http://msdn.microsoft.com/en-us/library/5zbwd3s3.aspx

This change requires update access to registry.

Related Topic