我有一个C#窗口服务,我正在其中创建ng-template
文件中的自定义事件源和日志名称,
ProjectInstaller.Designer.cs
,当我安装窗口服务时,日志名称显示在private void InitializeComponent()
{
this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
//
// serviceProcessInstaller1
//
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
//
// serviceInstaller1
//
this.serviceInstaller1.ServiceName = "DemoService";
this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
var eventLog1 = new System.Diagnostics.EventLog();
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource(
"MySource", "MyNewLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog";
//
// ProjectInstaller
//
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller1,
this.serviceInstaller1});
}
下,
现在,服务中所有未处理的异常是否都将以源'MySource`记录在Applications and Service Logs
下?
MyNewLog
当前它在protected override void OnStart(string[] args)
{
throw new NotImplementedException();
}
下记录,来源为“ Service1”
答案 0 :(得分:1)
好,配置EventLog到类构造函数中:
void InitiateEventLog(EventLog eventLog)
{
if (!EventLog.SourceExists("MySource"))
{
EventLog.CreateEventSource("MySource", "MyNewLog");
}
eventLog.Source = "MySource";
eventLog.Log = "MyNewLog";
}
您的构造函数应类似于:
public Service1()
{
InitiateEventLog(EventLog);
InitializeComponent();
}
然后,您可以使用OnStart
方法捕获未处理的异常,然后编写 CUSTOM 日志:
protected override void OnStart(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
EventLog.WriteEntry($"Unhundeled Exception occurred: {(e.ExceptionObject as Exception).Message}");
}