近几天用 C# 在对日志进行操作的时候,发现经常无法正常写入正确的日志条目,经过测试,发现这可能是 .NET 的一个 Bug ,重现/测试程序如下:
static void Main(string[] args)
...{
string sSource = "DotNetMySource";
string sLog = "DotNetMyLog";
![]()
//新建日志文件及源并写入一条日志
if(!EventLog.SourceExists(sSource))
...{
EventLog.CreateEventSource(sSource,sLog);
Console.WriteLine("Source Created");
}
EventLog log = new EventLog();
log.Source = sSource;
log.WriteEntry("Hello China");
Console.WriteLine("Log Entry Writed");
Console.ReadLine();
![]()
![]()
//删除刚才的建立日志文件及源
if(EventLog.SourceExists(sSource))
...{
EventLog.DeleteEventSource(sSource);
Console.WriteLine("Source Deleted");
}
else
...{
Console.WriteLine("Source Not Found");
}
if(EventLog.Exists(sLog))
...{
EventLog.Delete(sLog);
Console.WriteLine("Log Deleted");
}
else
...{
Console.WriteLine("Log Not Found");
}
Console.ReadLine();
![]()
//重新建立同样的日志文件及源
if(!EventLog.SourceExists(sSource))
...{
EventLog.CreateEventSource(sSource,sLog);
Console.WriteLine("Source Created");
}
log = new EventLog();
log.Source = sSource;
log.WriteEntry("Hello China Again");
Console.WriteLine("Log Entry Writed");
Console.ReadLine();
![]()
}
在程序运行的三个步骤中,你需要打开/关闭“日志查看器”以确定每次程序执行的结果(日志查看器中的刷新功能,不能刷新新建立的日志文件)。
在最后程序执行结束后,你会发现新写入的日志条目的“源”属性为空,而不是预计的 “DotNetMySource”。
甚至有时候会出现把日志写入到 Application 日志文件中的情况,且在日志查看器中会看到如下的消息(英文 OS):
The description for Event ID ( 0 ) in Source ( DotNetMySource ) cannot be
found. The local computer may not have the necessary registry information or
message DLL files to display messages from a remote computer. You may be
able to use the /AUXSOURCE= flag to retrieve this description; see Help and
Support for details. The following information is part of the event: Hello China Again
目前似乎没有别的解决办法,在 VS.NET 中直接删除日志文件,也会出现同样的问题,只有换用不同的 Source Name 和 Log Name 了,如果不删除,在写入新的 Log Entry 时好象没有这样的问题。
希望大家有时间测试一下,也希望 MS 的同志们确认是否是一个 Bug。
可能是在进程创建、进程删除、同个进程再创建,MS程序不允许吧?
这个问题好像见过,好像是需要重起一下……
应该是个已知问题……
应该可以了!
上面的源代码的显示效果是怎么做出来的?