.Net4.0,Windows 7(64位),基于C#Winform的应用程序。 这是编写事件日志的方法。但是,MS Eventviewer上没有显示事件日志。你有什么主意吗 ?
private static void WriteEventLogEntry(string message)
{
// Create an instance of EventLog
System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog();
// Check if the event source exists. If not create it.
if (!System.Diagnostics.EventLog.SourceExists("TestProgram"))
{
System.Diagnostics.EventLog.CreateEventSource("TestProgram", "Application");
}
// Set the source name for writing log entries.
eventLog.Source = "TestProgram";
// Create an event ID to add to the event log
int eventID = 8;
// Write an entry to the event log.
eventLog.WriteEntry(message,
System.Diagnostics.EventLogEntryType.Information,
eventID);
// Close the Event Log
eventLog.Close();
}
}
修改
我更改了以下代码。我可以看到事件日志而不以管理员身份运行。我还有一个问题。有两个日志,如“Log 1”和“Log 2”。我可以在查看器上看到“Log 1”。但是,我看不到“Log 2”。你有什么主意吗 ?
using System.Diagnostics;
namespace ImageDelegateSample
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MdiForm mainForm = null;
try
{
bool createdNew;
Mutex dup = new Mutex(true, "ImageDelegateSample", out createdNew);
if (createdNew)
{
// Log 1
WriteEventLogEntry("Loading", EventLogEntryType.Information);
mainForm = new MdiForm();
Application.Run(mainForm);
// Log 2
WriteEventLogEntry("Done Loading", EventLogEntryType.Information);
}
else
{
MessageBox.Show("already running.");
}
}
catch (Exception e)
{
// You probably want something a little more sophisticated than this
MessageBox.Show(e.Message, "An exception occurred:", MessageBoxButtons.OK, MessageBoxIcon.Error);
HandleError(e);
System.Environment.Exit(0);
}
}
static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
HandleError(e.Exception);
}
internal static void HandleError(Exception e)
{
string message = e.Message + "\n\n";
if (e.InnerException != null)
message += "Inner exception:\n" + e.InnerException.Message + "\n\n";
message += e.StackTrace;
MessageBox.Show(message, "An error has occurred:");
}
private static readonly string EventLogName = "Application";
private static readonly string EventLogSource = "ImageDelegateSample.exe";
private static void WriteEventLogEntry(string message, EventLogEntryType type)
{
// In the only function that does something
if (!EventLog.Exists(EventLogName))
{
EventLog.CreateEventSource(EventLogSource, EventLogName);
return;
}
else
{
// This doesn't write anything
EventLog.WriteEntry(EventLogSource,
message,
type);
}
}
}
}