我创建了一个 Windows 服务。我创建一个事件日志。
public Service1()
{
InitializeComponent();
this.ServiceName = ConfigurationManager.AppSettings.Get("ServiceName");
string sourceName = ConfigurationManager.AppSettings.Get("ServiceName");
string logName = ConfigurationManager.AppSettings["EventLogName"];
try
{
if (!System.Diagnostics.EventLog.Exists(sourceName))
System.Diagnostics.EventLog.CreateEventSource(sourceName, logName);
eventLog.Source = sourceName;
eventLog.Log = logName;
}
catch
{
eventLog.Source = "Application";
}
}
初始化期间,会安装服务但不会创建日志。日志条目位于Application
系统日志。
我错过了什么?
我使用进程安装程序进行安装
public ProjectInstaller()
{
InitializeComponent();
this.Installers.Add(GetServiceInstaller());
this.Installers.Add(GetServiceProcessInstaller());
}
private ServiceInstaller GetServiceInstaller()
{
serviceInstaller.ServiceName = GetConfigurationValue("ServiceName");
serviceInstaller.Description = GetConfigurationValue("Description");
serviceInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
return serviceInstaller;
}
private ServiceProcessInstaller GetServiceProcessInstaller()
{
serviceProcessinstaller.Account = ServiceAccount.LocalSystem;
return serviceProcessinstaller;
}
如何创建事件日志?
将您的代码更改为以下内容:
if (!System.Diagnostics.EventLog.SourceExists(source: sourceName))
{
System.Diagnostics.EventLog.CreateEventSource(source: sourceName, logName: logName);
}
注意根据 Microsoft 的 KB https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2008/y7x55536(v=vs.90)?redirectedfrom=MSDN,事件日志名称的前 8 个字符必须与计算机上的所有其他事件日志不同(因此,如果用户的计算机已有一个名为"Application"
那么你就无法创建一个新的EventLog
named "Applicat1"
or "ApplicationFoobar"
因为它们与内置的共享相同的 8 个字符Application
事件日志)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)