public void EventLogger_LoggingTest() { string message = "Error Message"; Exception ex = new Exception("Exception"); string messageFormat = "Message Format: message: {0}, exception: {1}"; ILog log = new EventLogger("ServiceStack.Logging.Tests", "Application"); Assert.IsNotNull(log); log.Debug(message); log.Debug(message, ex); log.DebugFormat(messageFormat, message, ex.Message); log.Error(message); log.Error(message, ex); log.ErrorFormat(messageFormat, message, ex.Message); log.Fatal(message); log.Fatal(message, ex); log.FatalFormat(messageFormat, message, ex.Message); log.Info(message); log.Info(message, ex); log.InfoFormat(messageFormat, message, ex.Message); log.Warn(message); log.Warn(message, ex); log.WarnFormat(messageFormat, message, ex.Message); }
/* initialises the service's event log, service parameters, and service status updater * The event log and source cannot be created and immediately used here as latency time * is needed to enable the log. Instead use the provided script 'LSAssetDataService-EventLog.ps1' * to create the log and source prior to starting the service. * Parameters are set from command line arguments passed in through 'args'. */ public LSAssetData(string[] args) { // INITIALISE SERVICE InitialiseComponents(); // initialises low level components from designer serviceDisplayName = new ServiceController(ServiceName).DisplayName; // display name created by project installer // create aggregates: EVENT LOG, PARAMETERS, SERVICE STATUS UPDATER log = new EventLogger(EventLogComponent, EventLogSource); parameters = new ServiceParameters(args, log); status = new ServiceStatusUpdater(this); // LOG details log.Info("Service Parameters:" + Environment.NewLine + "\tMonitored Service=" + parameters.MasterServiceName + Environment.NewLine + "\tInterval Minutes=" + parameters.IntervalMinutes + Environment.NewLine + "\tInterval Seconds=" + parameters.IntervalSeconds + Environment.NewLine + "\tTotal interval (milliseconds)=" + parameters.IntervalMilliseconds + Environment.NewLine + "\tTarget Folder Path=" + parameters.TargetFolderPath + Environment.NewLine + "\tDatabase Server=" + parameters.DatabaseServer + Environment.NewLine + "\tAsset Database=" + parameters.AssetDatabaseName + Environment.NewLine + "\tLS Database=" + parameters.LSDatabaseName + Environment.NewLine + "\tRFID Tag Prefix=" + parameters.RFIDCodePrefix + Environment.NewLine + "Event Logger:" + Environment.NewLine + "\tEvent Log Name=" + log.EventLogName + Environment.NewLine + "\tEvent Log Source=" + log.EventSourceName + Environment.NewLine + "Service Status Updater:" + Environment.NewLine + "\tCurrent Status=" + Enum.GetName(typeof(ServiceStatusUpdater.ServiceStateEnum), status.GetStatus) , EventLogger.EventIdEnum.INITIALISING); }
/// <summary> /// <c>Startup</c> /// The method caled by Topshelf to start the service running /// </summary> public void Start() { try { if (WatchSocket) { SocketListener = new Hl7SocketListener(ListenerPort, Parse) { RunAsService = true, AllowZeroTQ = AllowZeroTQ, DebugMode = DebugMode }; SocketListener.Go(); } if (WatchFileSystem) { FilesystemListener = new FilesystemListener(GetPlatformOs.Current == PlatformOs.Windows ? WinMonitorDirectory : NixMonitorDirectory, Parse) { RunAsService = true, Listening = true, DebugMode = DebugMode }; FilesystemListener.Go(); } EventLogger.Info("Service started"); } catch (Exception ex) { Console.WriteLine(ex); EventLogger.Error($"Failed to start service: {ex.Message}"); throw; } }
/// <summary> /// <c>Restart</c> /// Method called by Topshellf to restart the service /// </summary> public void Restart() { _pharmaserve.Dispose(); _pharmaserve = new Pharmaserve(_motDatabaseServer, GatewayIp, GatewayPort); _pharmaserve.Go(); EventLogger.Info("Service restarted"); }
public static T ReadConfig <T>(string fullFilePath) where T : ConfigurationBase { if (!File.Exists(fullFilePath)) { throw new FileNotFoundException($"Could not locate '{fullFilePath}'"); } EventLogger.Info($"Reading configuration from {fullFilePath}"); return(JsonFileIO.Read <T>(fullFilePath)); }
/// <summary> /// <c>WriteMessageToFile</c> /// Persist the message to a file /// </summary> /// <param name="message"></param> /// <param name="fileName"></param> public void WriteMessageToFile(string message, string fileName) { try { EventLogger.Info("Received message. Saving to file {0}", fileName); using (var file = new StreamWriter(fileName)) { file.Write(message); } } catch (Exception ex) { EventLogger.Error("Failed to write file {0}, {1}", fileName, ex.Message); } }
/// <summary> /// <c>Restart</c> /// Method called by Topshellf to restart the service /// </summary> public void Restart() { if (WatchSocket) { SocketListener.ShutDown(); SocketListener.Go(); } if (WatchFileSystem) { FilesystemListener.ShutDown(); FilesystemListener.Go(); } EventLogger.Info("Service restarted"); }
public static async Task Main(string[] args) { Logger.Info("Some message."); try { throw new Exception("Test exception message."); } catch (Exception ex) { Logger.Error(ex, "Exception is thrown."); } EventLogger.Info("Logon by {user} from {ip_address}", "Kenny", "127.0.0.1"); await Console.In.ReadLineAsync(); }
/// <summary> /// <c>StopListener</c> /// The method called by Topshelf to halt the service /// </summary> public void Stop() { if (WatchSocket) { SocketListener.ShutDown(); //SocketListener.Dispose(); } if (WatchFileSystem) { FilesystemListener.ShutDown(); FilesystemListener.Dispose(); } SaveConfiguration(); EventLogger.Info("sevice stopped"); }
// ON START - starts the service and server monitor, and executes the service for the first time protected override void OnStart(string[] args) { status.StartPending(); // START SERVER MONITOR monitor = new ServerMonitor(parameters.MasterServiceName, Log); // monitor the master service, OnStop disposes of this // START SERVICE timer // activates the service timer to trigger OnService() System.Timers.Timer serviceTimer = new System.Timers.Timer(); serviceTimer.Interval = parameters.IntervalMilliseconds; // must be less than Int32.MaxValue serviceTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnService); serviceTimer.Start(); // LOG STARTUP details log.Info("\t" + ServiceName + " (" + serviceDisplayName + ") started on " + Environment.MachineName + Environment.NewLine + "Server Monitor:" + Environment.NewLine + "\tMonitoring " + Environment.MachineName + " failover status" + Environment.NewLine + "File Writer:" + Environment.NewLine + "\tOutput Folder=" + AssetDataFileWriter.OutputFolderPath + Environment.NewLine + "\tArchive Folder=" + AssetDataFileWriter.ArchiveFolderPath + Environment.NewLine + "\tFiles To Retain When Archiving=" + AssetDataFileWriter.FilesToRetainWhenArchiving + Environment.NewLine + "\tFilename Prefix=" + AssetDataFileWriter.DataFilenamePrefix + Environment.NewLine + "\tFilename Extension=" + AssetDataFileWriter.DataFileType + Environment.NewLine + "Data Reader:" + Environment.NewLine + "\tDatabase Server=" + AssetDataReader.DatabaseServer + Environment.NewLine + "\tAsset Database=" + AssetDataReader.AssetDatabase + Environment.NewLine + "\tLS Database=" + AssetDataReader.LsDatabase , EventLogger.EventIdEnum.STARTING); // initiliase CUTOFF time - this variable stores the full date and time of the latest asset changein Agility. It is needed to provide a more accurate cuttoff than the fileLatestModifiedTime from the CORE file timestamp, which is accurate to the minute only. The precise latest modified time is used in the ReadData query instead of the timestamp from the file. This prevents unnecessary repeat reads of the latest record when it has not changed. LatestModifiedAssetTime = AssetDataFileWriter.RetrieveLatestModifiedFileTime(); status.Running(); // execute the service - note the monitor may not have started in which case wait for service timer to execute next onservice if (monitor.ServerStatus == ServerMonitor.ServerStatusEnum.ACTIVE) // do nothing if server is on STANDBY { OnService(); // otherwise execute the service } }
public void Start() { try { LoadConfiguration(); // "Data Source=PROXYPLAYGROUND;Initial Catalog=McKessonTestDb;User ID=sa;Password=$MOT2018" _connectString = $"Data Source={DbServer};Initial Catalog={DbName};User ID={DbUser};Password={DbPassword};"; _motDatabaseServer = new MotSqlServer(_connectString); _pharmaserve = new Pharmaserve(_motDatabaseServer, GatewayIp, GatewayPort); _pharmaserve.RefreshRate = RefreshRate; _pharmaserve.Go(); EventLogger.Info("Service started"); } catch (Exception ex) { Console.WriteLine(ex); EventLogger.Error($"Failed to start service: {ex.Message}"); throw; } }
public void EventLoggerLogInfo() { ManualResetEvent handle = new ManualResetEvent(false); try { EventLogger logger = new EventLogger(); logger.Log += (sender, args) => { Assert.AreEqual(EventLoggerEventType.Info, args.EventType); Assert.AreEqual("Info", args.Message); Assert.IsNull(args.Exception); handle.Set(); }; logger.Info("Info"); WaitHandle.WaitAll(new WaitHandle[] { handle }); } finally { handle.Close(); } }
/// <summary> /// <c>StopListener</c> /// The method called by Topshelf to halt the service /// </summary> public void Stop() { _pharmaserve.Stop(); EventLogger.Info("Sevice stopped"); }
public void WriteConfig(string fullFilePath) { JsonFileIO.Write(fullFilePath, this); EventLogger.Info($"Configuration saved to {fullFilePath}"); }