更多细节在这里。以下内容应至少在 Visual Studio 2017 和 Visual Studio 2019 中有效。
- 在 Visual Studio 的解决方案资源管理器中,双击您的服务组件,即派生自
ServiceBase. 这样做会在 [Design] 视图中打开组件。
- 打开 [Design] 视图后,按 F4(或菜单中的 View|Properties Window)打开 Properties 网格。
- 在“属性”网格中,将AutoLog属性设置为
false。这将阻止默认情况下将事件写入 Windows 应用程序日志。
- 如果您还没有这样做,请右键单击服务组件的 [Design] 视图中的任意位置,然后选择Add Installer菜单选项。
ProjectInstaller这会在您的解决方案中添加一个默认命名的组件。
- 请注意,新
ProjectInstaller的会自动打开到其各自的 [设计] 视图。要查看其代码,请在解决方案资源管理器中右键单击 ProjectInstaller.cs 文件,然后选择查看代码菜单选项。
- 将该文件的内容更改为如下所示。这将更新
EventLogInstaller以使用您选择的自定义日志名称。
using System.ComponentModel;
using System.Configuration.Install;
using System.Diagnostics;
namespace YourProjectNamespace
{
[RunInstaller(true)]
public partial class ProjectInstaller : Installer
{
public ProjectInstaller()
{
InitializeComponent();
EventLogInstaller installer = FindInstaller(this.Installers);
if (installer != null)
{
installer.Log = "YourEventLogName"; // enter your event log name here
}
}
private EventLogInstaller FindInstaller(InstallerCollection installers)
{
foreach (Installer installer in installers)
{
if (installer is EventLogInstaller)
{
return (EventLogInstaller)installer;
}
EventLogInstaller eventLogInstaller = FindInstaller(installer.Installers);
if (eventLogInstaller != null)
{
return eventLogInstaller;
}
}
return null;
}
}
}
- 最后一步是将服务组件绑定到您在步骤 6 中命名的自定义事件日志。为此,请在解决方案资源管理器中右键单击服务组件,然后选择查看代码菜单选项。将构造函数更新为以下内容:
public YourServiceName()
{
InitializeComponent();
// This ties the EventLog member of the ServiceBase base class to the
// YourEventLogName event log created when the service was installed.
EventLog.Log = "YourEventLogName";
}
- 安装服务时,应在系统上创建YourEventLogName 。如果事件查看器已经打开,您可能需要刷新它。如果它仍然不可见,您可能需要在其中记录一些内容(我不记得详细信息)。在任何情况下,要将日志信息从您的服务写入自定义事件日志,请使用
EventLog服务组件的成员,例如,
protected override void OnStart(string[] args)
{
EventLog.WriteEntry("The service was started successfully.", EventLogEntryType.Information);
}
protected override void OnStop()
{
EventLog.WriteEntry("The service was stopped successfully.", EventLogEntryType.Information);
}
protected override void OnShutdown()
{
EventLog.WriteEntry("The service was shutdown successfully", EventLogEntryType.Information);
}