public override FilterDecision Decide(LoggingEvent loggingEvent) { Exception ex = loggingEvent.ExceptionObject ?? DefaultException; bool fileSkipped = ExtensibleDisturbanceAnalysisEngine.IsFileSkippedException(ex); if (m_excludeFileSkippedExceptions && fileSkipped) { return(FilterDecision.Deny); } if (m_excludeEverythingElse && !fileSkipped) { return(FilterDecision.Deny); } return(FilterDecision.Neutral); }
private void ServiceHelper_ServiceStarted(object sender, EventArgs e) { ServiceHelperAppender serviceHelperAppender; RollingFileAppender fileAppender; TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; // Set current working directory to fix relative paths Directory.SetCurrentDirectory(FilePath.GetAbsolutePath("")); // Set up logging serviceHelperAppender = new ServiceHelperAppender(m_serviceHelper); fileAppender = new RollingFileAppender(); fileAppender.StaticLogFileName = false; fileAppender.AppendToFile = true; fileAppender.RollingStyle = RollingFileAppender.RollingMode.Composite; fileAppender.MaxSizeRollBackups = 10; fileAppender.PreserveLogFileNameExtension = true; fileAppender.MaximumFileSize = "1MB"; fileAppender.Layout = new PatternLayout("%date [%thread] %-5level %logger - %message%newline"); try { if (!Directory.Exists("Debug")) { Directory.CreateDirectory("Debug"); } fileAppender.File = @"Debug\openXDA.log"; } catch (Exception ex) { fileAppender.File = "openXDA.log"; m_serviceHelper.ErrorLogger.Log(ex); } fileAppender.ActivateOptions(); BasicConfigurator.Configure(serviceHelperAppender, fileAppender); // Set up heartbeat and client request handlers m_serviceHelper.AddScheduledProcess(ServiceHeartbeatHandler, "ServiceHeartbeat", "* * * * *"); m_serviceHelper.AddScheduledProcess(ReloadConfigurationHandler, "ReloadConfiguration", "0 0 * * *"); m_serviceHelper.ClientRequestHandlers.Add(new ClientRequestHandler("ReloadSystemSettings", "Reloads system settings from the database", ReloadSystemSettingsRequestHandler)); m_serviceHelper.ClientRequestHandlers.Add(new ClientRequestHandler("EngineStatus", "Displays status information about the XDA engine", EngineStatusHandler)); m_serviceHelper.ClientRequestHandlers.Add(new ClientRequestHandler("TweakFileProcessor", "Modifies the behavior of the file processor at runtime", TweakFileProcessorHandler)); m_serviceHelper.ClientRequestHandlers.Add(new ClientRequestHandler("MsgServiceMonitors", "Sends a message to all service monitors", MsgServiceMonitorsRequestHandler)); // Set up adapter loader to load service monitors m_serviceMonitors = new ServiceMonitors(); m_serviceMonitors.AdapterCreated += ServiceMonitors_AdapterCreated; m_serviceMonitors.AdapterLoaded += ServiceMonitors_AdapterLoaded; m_serviceMonitors.AdapterUnloaded += ServiceMonitors_AdapterUnloaded; m_serviceMonitors.Initialize(); // Set up the analysis engine m_extensibleDisturbanceAnalysisEngine = new ExtensibleDisturbanceAnalysisEngine(); // Set up separate thread to start the engine m_startEngineThread = new Thread(() => { const int RetryDelay = 1000; const int SleepTime = 200; const int LoopCount = RetryDelay / SleepTime; bool engineStarted = false; bool webUIStarted = false; while (true) { engineStarted = engineStarted || TryStartEngine(); webUIStarted = webUIStarted || TryStartWebUI(); if (engineStarted && webUIStarted) { break; } for (int i = 0; i < LoopCount; i++) { if (m_serviceStopping) { return; } Thread.Sleep(SleepTime); } } }); m_startEngineThread.Start(); }
private void ServiceHelper_ServiceStarted(object sender, EventArgs e) { const int RetryDelay = 1000; const int SleepTime = 200; const int LoopCount = RetryDelay / SleepTime; ServiceHelperAppender serviceHelperAppender; RollingFileAppender fileAppender; // Set current working directory to fix relative paths Directory.SetCurrentDirectory(FilePath.GetAbsolutePath("")); // Set up logging serviceHelperAppender = new ServiceHelperAppender(m_serviceHelper); fileAppender = new RollingFileAppender(); fileAppender.StaticLogFileName = false; fileAppender.AppendToFile = true; fileAppender.RollingStyle = RollingFileAppender.RollingMode.Composite; fileAppender.MaxSizeRollBackups = 10; fileAppender.PreserveLogFileNameExtension = true; fileAppender.MaximumFileSize = "1MB"; fileAppender.Layout = new PatternLayout("%date [%thread] %-5level %logger - %message%newline"); try { if (!Directory.Exists("Debug")) { Directory.CreateDirectory("Debug"); } fileAppender.File = @"Debug\openXDA.log"; } catch (Exception ex) { fileAppender.File = "openXDA.log"; m_serviceHelper.ErrorLogger.Log(ex); } fileAppender.ActivateOptions(); BasicConfigurator.Configure(serviceHelperAppender, fileAppender); // Set up heartbeat and client request handlers m_serviceHelper.AddScheduledProcess(ServiceHeartbeatHandler, "ServiceHeartbeat", "* * * * *"); m_serviceHelper.AddScheduledProcess(ReloadConfigurationHandler, "ReloadConfiguration", "0 0 * * *"); m_serviceHelper.ClientRequestHandlers.Add(new ClientRequestHandler("ReloadSystemSettings", "Reloads system settings from the database", ReloadSystemSettingsRequestHandler)); m_serviceHelper.ClientRequestHandlers.Add(new ClientRequestHandler("EngineStatus", "Displays status information about the XDA engine", EngineStatusHandler)); m_serviceHelper.ClientRequestHandlers.Add(new ClientRequestHandler("TweakFileProcessor", "Modifies the behavior of the file processor at runtime", TweakFileProcessorHandler)); m_serviceHelper.ClientRequestHandlers.Add(new ClientRequestHandler("MsgServiceMonitors", "Sends a message to all service monitors", MsgServiceMonitorsRequestHandler)); // Set up adapter loader to load service monitors m_serviceMonitors = new ServiceMonitors(); m_serviceMonitors.AdapterCreated += ServiceMonitors_AdapterCreated; m_serviceMonitors.AdapterLoaded += ServiceMonitors_AdapterLoaded; m_serviceMonitors.AdapterUnloaded += ServiceMonitors_AdapterUnloaded; m_serviceMonitors.Initialize(); // Set up the analysis engine m_extensibleDisturbanceAnalysisEngine = new ExtensibleDisturbanceAnalysisEngine(); // Set up separate thread to start the engine m_startEngineThread = new Thread(() => { while (!TryStartEngine()) { for (int i = 0; i < LoopCount; i++) { if (m_serviceStopping) { return; } Thread.Sleep(SleepTime); } } }); m_startEngineThread.Start(); CategorizedSettingsElementCollection systemSettings = ConfigurationFile.Current.Settings["systemSettings"]; CategorizedSettingsElementCollection securityProvider = ConfigurationFile.Current.Settings["securityProvider"]; ValidateAccountsAndGroups(new AdoDataConnection("securityProvider")); systemSettings.Add("CompanyName", "Grid Protection Alliance", "The name of the company who owns this instance of the openMIC."); systemSettings.Add("CompanyAcronym", "GPA", "The acronym representing the company who owns this instance of the openMIC."); systemSettings.Add("WebHostURL", "http://localhost:8080", "The web hosting URL for remote system management."); systemSettings.Add("DateFormat", "MM/dd/yyyy", "The default date format to use when rendering timestamps."); systemSettings.Add("TimeFormat", "HH:mm.ss.fff", "The default time format to use when rendering timestamps."); systemSettings.Add("BootstrapTheme", "Content/bootstrap.min.css", "Path to Bootstrap CSS to use for rendering styles."); systemSettings.Add("DefaultDialUpRetries", 3, "Default dial-up connection retries."); systemSettings.Add("DefaultDialUpTimeout", 90, "Default dial-up connection timeout."); systemSettings.Add("DefaultFTPUserName", "anonymous", "Default FTP user name to use for device connections."); systemSettings.Add("DefaultFTPPassword", "anonymous", "Default FTP password to use for device connections."); systemSettings.Add("DefaultRemotePath", "/", "Default remote FTP path to use for device connections."); systemSettings.Add("DefaultLocalPath", "", "Default local path to use for file downloads."); DefaultWebPage = systemSettings["DefaultWebPage"].Value; Model = new AppModel(); Model.Global.CompanyName = systemSettings["CompanyName"].Value; Model.Global.CompanyAcronym = systemSettings["CompanyAcronym"].Value; Model.Global.ApplicationName = "openXDA"; Model.Global.ApplicationDescription = "open Meter Information Collection System"; Model.Global.ApplicationKeywords = "open source, utility, software, meter, interrogation"; Model.Global.DateFormat = systemSettings["DateFormat"].Value; Model.Global.TimeFormat = systemSettings["TimeFormat"].Value; Model.Global.DateTimeFormat = $"{Model.Global.DateFormat} {Model.Global.TimeFormat}"; Model.Global.BootstrapTheme = systemSettings["BootstrapTheme"].Value; try { // Attach to default web server events WebServer webServer = WebServer.Default; webServer.StatusMessage += WebServer_StatusMessage; // Define types for Razor pages - self-hosted web service does not use view controllers so // we must define configuration types for all paged view model based Razor views here: webServer.PagedViewModelTypes.TryAdd("Users.cshtml", new Tuple <Type, Type>(typeof(UserAccount), typeof(SecurityHub))); webServer.PagedViewModelTypes.TryAdd("Groups.cshtml", new Tuple <Type, Type>(typeof(SecurityGroup), typeof(SecurityHub))); webServer.PagedViewModelTypes.TryAdd("Settings.cshtml", new Tuple <Type, Type>(typeof(Setting), typeof(DataHub))); webServer.PagedViewModelTypes.TryAdd("Devices.cshtml", new Tuple <Type, Type>(typeof(Meter), typeof(DataHub))); webServer.PagedViewModelTypes.TryAdd("Stations.cshtml", new Tuple <Type, Type>(typeof(MeterLocation), typeof(DataHub))); webServer.PagedViewModelTypes.TryAdd("MeterGroups.cshtml", new Tuple <Type, Type>(typeof(Group), typeof(DataHub))); webServer.PagedViewModelTypes.TryAdd("GroupMeterView.cshtml", new Tuple <Type, Type>(typeof(GroupMeterView), typeof(DataHub))); webServer.PagedViewModelTypes.TryAdd("Lines.cshtml", new Tuple <Type, Type>(typeof(LineView), typeof(DataHub))); webServer.PagedViewModelTypes.TryAdd("MeterLine.cshtml", new Tuple <Type, Type>(typeof(MeterLine), typeof(DataHub))); webServer.PagedViewModelTypes.TryAdd("Channel.cshtml", new Tuple <Type, Type>(typeof(Channel), typeof(DataHub))); webServer.PagedViewModelTypes.TryAdd("DashSettings.cshtml", new Tuple <Type, Type>(typeof(DashSettings), typeof(DataHub))); webServer.PagedViewModelTypes.TryAdd("AlarmSettings", new Tuple <Type, Type>(typeof(AlarmRangeLimitView), typeof(DataHub))); // Initiate pre-compile of base templates if (AssemblyInfo.EntryAssembly.Debuggable) { RazorEngine <CSharpDebug> .Default.PreCompile(HandleException); RazorEngine <VisualBasicDebug> .Default.PreCompile(HandleException); } else { RazorEngine <CSharp> .Default.PreCompile(HandleException); RazorEngine <VisualBasic> .Default.PreCompile(HandleException); } // Create new web application hosting environment m_webAppHost = WebApp.Start <Startup>(systemSettings["WebHostURL"].Value); } catch (Exception ex) { HandleException(new InvalidOperationException($"Failed to initialize web hosting: {ex.Message}", ex)); } }
protected override void Append(LoggingEvent loggingEvent) { object threadID; object meterKey; string renderedMessage; Exception ex; UpdateType updateType; // If the service helper has been disposed, // do not log the event if ((object)m_serviceHelper == null) { return; } // Determine the update type based on the log level if (loggingEvent.Level.Value >= Level.Error.Value) { updateType = UpdateType.Alarm; } else if (loggingEvent.Level.Value >= Level.Warn.Value) { updateType = UpdateType.Warning; } else if (loggingEvent.Level.Value >= Level.Info.Value) { updateType = UpdateType.Information; } else { return; } // Determine the thread ID from the thread's context threadID = Thread.CurrentThread.ManagedThreadId; meterKey = ThreadContext.Properties["Meter"]; // Get the message and exception object renderedMessage = loggingEvent.RenderedMessage; ex = loggingEvent.ExceptionObject; // If the user didn't supply a message, // attempt to use the exception message instead if (string.IsNullOrEmpty(renderedMessage)) { renderedMessage = loggingEvent.GetExceptionString(); } // Do not log FileSkippedExceptions // to the error log or the status log if (ExtensibleDisturbanceAnalysisEngine.IsFileSkippedException(ex)) { if (meterKey == null) { m_serviceHelper.UpdateStatus(updateType, false, "[{0}] {1}{2}", threadID, renderedMessage, Environment.NewLine); } else { m_serviceHelper.UpdateStatus(updateType, false, "[{0}] {{{1}}} {2}{3}", threadID, meterKey, renderedMessage, Environment.NewLine); } return; } // If the event was an exception event, // also log to the service helper's error log if ((object)ex != null) { if ((object)m_serviceHelper.ErrorLogger != null) { m_serviceHelper.ErrorLogger.Log(ex); } if (string.IsNullOrEmpty(renderedMessage)) { renderedMessage = ex.Message; } } // Send the message to clients via the service helper if (string.IsNullOrEmpty(renderedMessage)) { m_serviceHelper.UpdateStatusAppendLine(updateType, ""); } else if (meterKey == null) { m_serviceHelper.UpdateStatusAppendLine(updateType, "[{0}] {1}", threadID, renderedMessage); } else { m_serviceHelper.UpdateStatusAppendLine(updateType, "[{0}] {{{1}}} {2}", threadID, meterKey, renderedMessage); } }