c# - 安装服务时如何注册事件日志并向其写入初始消息?

标签 c# service event-log

我正在按照以下说明进行操作:

http://msdn.microsoft.com/en-us/library/9k985bc9.aspx - 如何创建服务

http://msdn.microsoft.com/en-us/library/ddhy0byf.aspx - 如何:将安装程序添加到您的服务应用程序

然后我使用提升的命令窗口和命令 installutil.exe -i WindowsService1.exe

安装该服务

这会完美地构建并安装服务和所有内容。

但是,我想向我的服务添加一个日志,这导致我想要创建事件日志源,并在安装程序中向其写入初始消息(因为安装程序将以提升的权限运行,而实际的服务可能不会)

因此,我将以下内容添加到安装程序代码中 (projectinstaller.cs)

public ProjectInstaller()
{
    InitializeComponent();

    if (!System.Diagnostics.EventLog.SourceExists("TestService"))
    {
        System.Diagnostics.EventLog.CreateEventSource(
            "TestService Service", "TestService");
    }
    System.Diagnostics.EventLog TestEventLog = new System.Diagnostics.EventLog();
    TestEventLog.Source = "TestService ServiceInstaller";
    TestEventLog.Log = "TestService";

    TestEventLog.WriteEntry("New log created");
}

这仍然可以构建,但现在installutil.exe -i WindowsService1.exe(仍在以提升的权限运行)抛出以下错误:

An exception occurred during the Install phase.
System.InvalidOperationException: Unable to create an instance of the WindowsService1.ProjectInstaller installer type.
The inner exception System.Reflection.TargetInvocationException was thrown with the following error message: Exception has been thrown by the target of an invocation..
The inner exception System.ArgumentException was thrown with the following error message: Log TestService has already been registered as a source on the local computer..

Google 让我相信这是 Windows RE 创建日志时出现的某种形式的权限错误,并让我找到了一个解决方案,涉及手动将内容写入注册表。不过,如果有更好的方法(例如,使用 native C# 方法来使其正常工作),我宁愿不要在注册表中乱搞。

安装服务时如何注册日志并写入初始消息?

最佳答案

异常(exception)是告诉您确切问题是什么。最后一行内容为:

The inner exception System.ArgumentException was thrown with the following error message: Log TestService has already been registered as a source on the local computer..

您正在尝试创建一个已经存在的源。

参见my answer to a similar question了解详情。

关于c# - 安装服务时如何注册事件日志并向其写入初始消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18187532/

相关文章:

javascript - 多个 Controller 操纵 Angular 指令中的内容?

c# - 记录 Windows 服务

c# - 如何在 C# 和 TPL 中并行处理事件

c# - 获取 Windows 中某个键的 'Shift' 表示

Python、Windows服务导入报错

powershell - 如何使用Powershell获取事件消息?

powershell - 如何使用powershell根据特定成员确定集合中对象的频率

c# - 在WPF中如何防止ScrollViewer内的控件展开

c# - 制作一个可重用的 GroupBy 函数

android - 如何识别上次使用 Android 设备的时间