![](/img/trans.png)
[英]EventLog WriteEntry not does not write into EventViewer in C#
[英]Write to Application EventLog in C#
我想在事件查看器中为许多不同的事件编写自定义源。
我希望日志名称为“Application”,源名称为“DDG ServiceWare”。 我查看了 MSDN 上的文档并做了这个:
private static void _writeToApplicationEventLog(string logMessage, int eventID)
{
if(!EventLog.SourceExists("DDG ServiceWare"))
{
EventSourceCreationData exitEvents = new EventSourceCreationData("DDG ServiceWare", "Application");
EventLog.CreateEventSource(exitEvents);
}
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "DDG ServiceWare";
eventLog.WriteEntry(logMessage, EventLogEntryType.Error, eventID);
}
}
但是,当我运行它时,出现异常:
System.dll 中发生类型为“System.ArgumentException”的未处理异常源“DDG ServiceWare”未在日志“应用程序”中注册。 (它在日志 'DDG ServiceWare' 中注册。)" Source 和 Log 属性必须匹配,或者您可以将 Log 设置为空字符串,它将自动与 Source 属性匹配。
即使我更改EventSourceCreationData exitEvents = new EventSourceCreationData("DDG ServiceWare", "Application");
到EventSourceCreationData exitEvents = new EventSourceCreationData("DDG ServiceWare", "DDG ServiceWare");
我在这里做错了什么?
您可能需要考虑像 SeriLog 这样的 package,这将使日志记录变得更加容易(不仅是事件日志,还有文件和其他目的地)。 看看这个https://github.com/serilog/serilog/wiki/Writing-Log-Events
我为你创建了例子
void Main()
{
_writeToApplicationEventLog("test", 123, EventLogEntryType.Error);
_writeToApplicationEventLog("test", 123, EventLogEntryType.Warning);
_writeToApplicationEventLog("test", 123, EventLogEntryType.Information);
}
private static void _writeToApplicationEventLog(string logMessage, int eventID, EventLogEntryType logType)
{
string sourceName = "SampleApplicationSource";
string myLogName = "myNewLog";
string messageFile = "customlog.log";
if (!EventLog.SourceExists(sourceName))
{
EventSourceCreationData mySourceData = new EventSourceCreationData(sourceName, myLogName);
mySourceData.MessageResourceFile = messageFile;
mySourceData.CategoryResourceFile = messageFile;
mySourceData.CategoryCount = 1;
mySourceData.ParameterResourceFile = messageFile;
EventLog.CreateEventSource(mySourceData);
}
myLogName = EventLog.LogNameFromSourceName(sourceName,".");
using (EventLog eventLog = new EventLog(myLogName, ".", sourceName))
{
eventLog.Source = sourceName;
eventLog.WriteEntry(logMessage, logType, eventID);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.