C# EventLog WriteEntry不写入指定的日志,而是写入应用程序日志
我有一个应用程序,我想将条目写入事件日志 记录器是通过MEF实例化的。 我创建了一个派生类,以便在使用它之前能够执行日志初始化 我的代码如下:C# EventLog WriteEntry不写入指定的日志,而是写入应用程序日志,c#,event-log,C#,Event Log,我有一个应用程序,我想将条目写入事件日志 记录器是通过MEF实例化的。 我创建了一个派生类,以便在使用它之前能够执行日志初始化 我的代码如下: public class WinEventLog : EventLog, ILogger { private const string LOG_SourceName = "DataGen_Source"; private const string LOG_SysLogName = "Pool_Log"; private bool
public class WinEventLog : EventLog, ILogger
{
private const string LOG_SourceName = "DataGen_Source";
private const string LOG_SysLogName = "Pool_Log";
private bool _isInitialized = false;
public WinEventLog()
: base()
{
Initialize();
}
public void LogMessage(MessageLevel level, string message)
{
WriteEntry(message, level.EventLogType());
}
public void LogMessage(string source, MessageLevel level, string message)
{
WriteEntry(source, message, level.EventLogType());
}
public void Initialize()
{
if (!_isInitialized)
{
this.BeginInit();
this.EndInit();
if (!System.Diagnostics.EventLog.SourceExists(LOG_SourceName))
{
System.Diagnostics.EventLog.CreateEventSource(
LOG_SourceName, LOG_SysLogName);
}
Source = LOG_SourceName;
Log = LOG_SysLogName;
_isInitialized = true;
}
}
}
但是,记录器不会写入我指定的日志Pool_log,而是写入应用程序日志
知道为什么会这样吗
编辑 我引用了其他项目中完全相同的组件,在这种情况下,它写入了正确的事件日志 我很困惑
谢谢您似乎正在创建源代码,但没有创建实际的日志。例如,如果要创建SQLEventLog,我将执行以下操作
public bool CreateLog(string strLogName)
{
bool Result = false;
try
{
System.Diagnostics.EventLog.CreateEventSource(strLogName, strLogName);
System.Diagnostics.EventLog SQLEventLog =
new System.Diagnostics.EventLog();
SQLEventLog.Source = strLogName;
SQLEventLog.Log = strLogName;
SQLEventLog.Source = strLogName;
SQLEventLog.WriteEntry("The " + strLogName + " was successfully
initialize component.", EventLogEntryType.Information);
Result = true;
}
catch
{
Result = false;
}
return Result;
}
如果有帮助,请告诉我。。看起来您缺少事件日志创建您可以尝试以下操作:
evntSource = "MySource";
evntLog = "MyLog"; //This replace Application!
evntEvent = "My Event";
if (!EventLog.SourceExists(evntSource))
EventLog.CreateEventSource(evntSource,evntLog);
EventLog.WriteEntry(evntSource,evntEvent);
您的错误可能与权限有关。检查事件源的注册表项的权限 最后,您不应该使用WriteEntry,您将遇到安全异常和其他问题
在我看来,您应该使用WriteEvent,请参见:检查事件日志源是否不长,是否不包含特殊的有意义的字符,例如。\or/ 在我的例子中,这是事件进入应用程序日志而不是指定的自定义日志的原因
public static void EventLogWrite(string Source, string Message, short categoryID, int eventID, EventLogEntryType entryType)
{
#if !DEBUG
if (!EventLog.SourceExists(Source))
EventLog.CreateEventSource(Source.RefineText(), "My Log Name");
EventLog.WriteEntry(Source.RefineText(), Message.TrimText(3000), entryType, eventID, categoryID);
#endif
}
对不起,您在哪一行创建事件日志?据我所知,您也只需创建源代码,然后分配源代码和日志,最后写入日志。顺便说一句,日志是由我的代码创建的,因为我看到它(它只是空的,所有条目都进入应用程序),所以我遇到了完全相同的问题。完全相同的组件可以在一个项目中写入指定的事件源,但不能在另一个项目中写入任何内容到标准应用程序日志中。只是遇到了这个问题-通过重新启动解决了这个问题。如果最初在“应用程序”下创建源,然后将其更改为“CustomApp”,则需要重新启动系统才能正常运行;在重新启动之前,您的事件将继续出现在“应用程序”下。@Mike重新启动也对我起作用。我甚至卸载了我创建的服务,检查了VisualStudio添加的事件记录器安装程序的属性,删除了注册表项。最后尝试重新启动。成功了。