c# – 记录Windows服务

我有以下代码用于记录我通过在线研究找到的Windows服务.
它在我的服务类内部完成之前就像在下面初始化一样.

public GBBInvService()
        {
            InitializeComponent();
            if (!System.Diagnostics.EventLog.SourceExists("MyLogSource"))
                System.Diagnostics.EventLog.CreateEventSource("MyLogSource",
                                                                      "MyDoLog");
            eventLog1.Source = "MyLogSource";
            eventLog1.Log = "MyDoLog";
        }

记录时的代码:

eventLog1.WriteEntry("GBBInvService Service Started");

然而,我的顾问却反对我.他的评论如下:

我会避免让服务在运行时创建事件源.这要求服务以高权限运行(即,比实际需要更多地访问计算机).设置Windows事件日志源实际上是一个安装时间作业.您可以将事件日志安装程序添加到项目安装程序文件(以及服务安装程序),然后事件源将始终存在

这个建议的问题是我无法找到在项目安装程序文件中创建日志的任何示例.我也尝试将此日志创建部分移动到我的项目安装程序中,但之后它不会让我从我的Web服务cs页面调用或写入eventlog1.他还建议使用log4net,但这对我来说是一个新的东西,并且很难掌握.刚刚完成我的第一个Windows服务项目,我对Windows服务仍然很陌生,并且非常感谢在项目安装程序中创建日志的任何方向,从我的服务cs页面或在log4net上的任何抬头写入它.

解决方法:

您的顾问是正确的,在服务中这样做是个坏主意.

以下是在安装程序中创建事件源的方法:

http://blogs.msdn.com/b/helloworld/archive/2008/12/11/creating-an-event-log.aspx?Redirected=true

简短版本:子类安装程序,并在子类安装程序的构造函数中创建事件日志源.

UPDATE

从链接:

After the service installer is executed, the log is ‘registered’, but not created yet. To create it, one event must be written. If the service runs using a restricted user account, that account may not have enough security permission to write the first log, as the log need to be created.

示例代码未显示正在编写的一个事件.确保你这样做.

When installing the service, the user must run the installer as Administrator

确保以管理员身份运行安装程序.

来自你的评论:

Service wouldn’t start.

查看事件日志,了解它未启动的原因.也许是抛出一个例外,例如如果您没有在安装程序中编写一个事件,或者您没有以管理员身份运行安装程序.

上一篇:c# – 在Log4Net中找不到Logger时设置默认日志


下一篇:c# – 使用Log4net实现彩色日志