繁体   English   中英

如何写入自定义事件日志?

[英]How to write to a custom event log?

我正在尝试将我的.Net Windows服务转到自定义事件日志。 我正在使用EventLogInstaller在安装应用程序时创建事件日志和源。 在这里读到,Windows注册源需要一段时间,因此他们建议您在尝试写入日志之前重新启动应用程序。

由于这是Windows服务,我不想强​​制重新启动计算机或让用户手动启动服务,因此我使用此代码等待日志存在,然后自动启动服务。

while (!(EventLog.Exists("ManageIT") || EventLog.SourceExists("ManageIT Client Service")))
{
    Thread.Sleep(1000);
}

System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController("ManageIT.Client.Service");
controller.Start();

我的问题是来自服务的事件仍然写入应用程序日志,虽然我可以在注册表编辑器中看到我的自定义日志,但它不会显示在Windows 7事件查看器中。

任何帮助都感激不尽。

默认情况下,安装服务时,源会与应用程序日志关联。 如果我们稍后更改此关联,则系统需要重新启动。

但是,通过在服务类(继承自servicebase的类)构造函数中将autolog属性设置为false,我们可以阻止服务与应用程序日志的关联。 http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.autolog.aspx

试试这个片段:

编辑 - 警告:如果运行代码的用户没有管理员权限,则会抛出异常。 由于这种情况(如果用户不具备这些权限),最佳做法应该是假设日志存在,并简单地写入它。 请参阅: 找不到源,但无法搜索部分或全部事件日志

if (!EventLog.SourceExists("MyApplicationEventLog"))
{
    EventSourceCreationData eventSourceData = new EventSourceCreationData("MyApplicationEventLog", "MyApplicationEventLog");
    EventLog.CreateEventSource(eventSourceData);
}

using (EventLog myLogger = new EventLog("MyApplicationEventLog", ".", "MyApplicationEventLog"))
{
    myLogger.WriteEntry("Error message", EventLogEntryType.Error);
    myLogger.WriteEntry("Info message", EventLogEntryType.Information);
}

听起来你正在写这样的事件日志:

 EventLog.WriteEntry("Source", "Message");

这将写入应用程序日志。

如果您在创建myLogger时使用simons post中的代码,则可以指定日志的名称。

我做了这样的事情:

        var logName = EventLog.LogNameFromSourceName("MyApp", Environment.MachineName);

         //delete the source if it associated with the wrong Log
        if (!string.IsNullOrEmpty(logName) & logName != "MyLog")
        {
            EventLog.DeleteEventSource("MyApp", Environment.MachineName);
        }

        if (!EventLog.SourceExists("MyApp"))
        {
            EventLog.CreateEventSource("MyApp", "MyLog");
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM