在Windows服务程序中记录事件 [英] Logging Events in a Windows Service Program

查看:144
本文介绍了在Windows服务程序中记录事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个Windows服务程序,我希望我的错误严格写入Windows事件日志。所以我按照代码项目文章中的这些步骤:

I have created a Windows service program and I want my error to strictly be written to the Windows eventLog. So I followed these steps from code project article:

http ://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx

但是我没有看到我写的任何自定义日志消息当我启动或停止服务时,在事件查看器窗口中创建的事件日志。
另外如何指定消息是由于错误还是仅仅是信息?

But I don't see any of the custom log messages I wrote in the event logs created in the event viewer window when I start or stop the service. Also how do I specify whether the message was due to an error or is just info?

推荐答案

首先, a href =http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx =noreferrer> MSDN 是您的朋友。确保您查看链接,因为有一些值得了解的潜在问题。

First, MSDN is your friend. Make sure you check out the link, as there are some potential gotchas worth knowing.

本质上,您创建一个EventLog对象:

Essentially, you create an EventLog object:

this.ServiceName = "MyService";
this.EventLog = new System.Diagnostics.EventLog();
this.EventLog.Source = this.ServiceName;
this.EventLog.Log = "Application";

如果上述源不存在,您还需要创建源代码:

You also need to create a source, if the above source doesn't exist:

((ISupportInitialize)(this.EventLog)).BeginInit();
if (!EventLog.SourceExists(this.EventLog.Source))
{
    EventLog.CreateEventSource(this.EventLog.Source, this.EventLog.Log);
}
((ISupportInitialize)(this.EventLog)).EndInit();

然后只需使用它:

this.EventLog.WriteEntry("My Eventlog message.", EventLogEntryType.Information);

其实很简单。

这篇关于在Windows服务程序中记录事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆