记录到自定义事件日志(C#应用程序,但使用win32 API)
由于.NET EventLog类的限制,我有一些代码使用PInvoke记录到应用程序日志中。代码可以正常工作 但现在,我想登录到自定义事件日志。因此,我尝试将RegisterEventSource的第二个参数更改为“companyX”(我的自定义日志)。它正确地写入了“companyX”(而不是应用程序日志),但它也将源字段(单个日志条目的)设置为“companyX”,这不是我想要的 那么,我如何修改代码以:记录到自定义事件日志(C#应用程序,但使用win32 API),c#,pinvoke,event-log,C#,Pinvoke,Event Log,由于.NET EventLog类的限制,我有一些代码使用PInvoke记录到应用程序日志中。代码可以正常工作 但现在,我想登录到自定义事件日志。因此,我尝试将RegisterEventSource的第二个参数更改为“companyX”(我的自定义日志)。它正确地写入了“companyX”(而不是应用程序日志),但它也将源字段(单个日志条目的)设置为“companyX”,这不是我想要的 那么,我如何修改代码以: 使用新的自定义事件日志(“companyX”),但 使用正确的源值(“MyApp”)
- 使用新的自定义事件日志(“companyX”),但
- 使用正确的源值(“MyApp”)
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);
}
}
哦,这不是问题的重复:
因为我必须用PInvoke来做这个 您必须创建一个名为MyApp的源,并将其映射到您的日志“CompanyX” 本文将详细介绍如何创建事件源w/.Net Framework
此更改需要对注册表进行更新访问。什么版本的.NET,限制是什么?.NET 3.5。限制是Windows将“用户”字段设置为“N/A”,而不是Windows用户(不可能按用户名进行分组/排序…对于拥有80个并发终端服务器用户的客户来说是个大问题…)猜得好!我在原来的问题上补充说,自定义日志的创建是由安装程序(WIX).MSI处理的。