public static EventLog CreateEventLog(string name) { string eventLogName = string.Empty; try { eventLogName = HostingEnvironment.ApplicationVirtualPath.Trim("/".ToCharArray()); if (string.IsNullOrEmpty(eventLogName)) { eventLogName = HostingEnvironment.SiteName; } } catch { // not running under a hosted environment } if (string.IsNullOrEmpty(eventLogName)) { eventLogName = name; } if (string.IsNullOrEmpty(eventLogName)) { eventLogName = "SnCore"; } if (!EventLog.SourceExists(eventLogName)) { EventSourceCreationData data = new EventSourceCreationData(eventLogName, "Application"); EventLog.CreateEventSource(data); } EventLog result = new EventLog(); result.Log = "Application"; result.Source = eventLogName; return(result); }
private static void CreateEventLogSource(string serviceName, string machineName, string logName) { if (EventLog.SourceExists(serviceName)) { return; } try { var permission = new EventLogPermission(EventLogPermissionAccess.Administer, machineName); permission.Assert(); var eventSourceCreationData = new EventSourceCreationData(serviceName, logName) { MachineName = machineName }; EventLog.CreateEventSource(eventSourceCreationData); } catch (Exception e) { Log.Error(e, e.Message); } }
internal static void WriteToEventLog(Exception exception) { if (exception == null) { throw new ArgumentNullException(nameof(exception)); } using (EventLog eventLog = new EventLog("Application")) { if (!EventLog.SourceExists("PRex", ".")) { EventSourceCreationData data = new EventSourceCreationData("PRex", "Application") { MachineName = "." }; EventLog.CreateEventSource(data); } eventLog.Source = "PRex"; eventLog.WriteEntry(exception.ToString(), EventLogEntryType.Error); } }
public static void CreateEventLog() { // creates the event log and if it exists deletes it and then creates it try { //// delete the event log //if (EventLog.Exists(EventLogName)) //{ // EventLog.Delete(EventLogName); //} // create the eventlog if it does not exist if (!EventLog.Exists(EventLogName)) { EventSourceCreationData creationData = new EventSourceCreationData(EventLogName, EventLogName); creationData.MachineName = "."; EventLog.CreateEventSource(creationData); // set the event log to overwrite as needed AEEventLog.ModifyOverflowPolicy(OverflowAction.OverwriteAsNeeded, 0); } // get a handle to the event log AEEventLog = new EventLog(); AEEventLog.Source = EventLogName; AEEventLog.Log = EventLogName; } catch (Exception e) { // error writing to our custom event log so write an error to the Application log EventLog ApplicationLog = new EventLog(); ApplicationLog.Source = "AppEngineError"; ApplicationLog.WriteEntry(Process.GetCurrentProcess().ProcessName + ".CreateEventLog: " + e.Message, EventLogEntryType.Error); if (e.Message.ToUpper().Contains("NOT ALLOWED")) { ApplicationLog.WriteEntry(Process.GetCurrentProcess().ProcessName + " must be run with Administrator privledges.", EventLogEntryType.Error); } throw new Exception("CreateEventLog: " + e.Message); } } // CreateEventLog
static AppEventLogger() { if (IsAdministrator == true) { SelfTesterSourceExists = EventLog.SourceExists(SelfTesterSourceName); if (!SelfTesterSourceExists) { var sourceCreationData = new EventSourceCreationData(SelfTesterSourceName, SelfTesterEventLogName); EventLog.CreateEventSource(sourceCreationData); SelfTesterSourceExists = true; } else { using (var testerEventLog = new EventLog(SelfTesterEventLogName, ".", SelfTesterSourceName)) { testerEventLog.Clear(); } } } else { SelfTesterSourceExists = false; } }
public void Add(String Source, String _Content, EventLogEntryType _Type) { String LogName = ConfigurationManager.AppSettings["ServiceName"]; if (String.IsNullOrEmpty(LogName)) { LogName = "yueyaCms.Service"; } String MachineName = "."; if (!EventLog.SourceExists(Source, MachineName)) { var SourceEntity = new EventSourceCreationData(Source, LogName) { MachineName = MachineName }; EventLog.CreateEventSource(SourceEntity); } new EventLog(LogName, MachineName, Source).WriteEntry(_Content, _Type, Thread.CurrentContext.ContextID); }
private static void WriteLog(string zsModule, string zsSource, string zsMsg, EventLogEntryType eType) { try { zsSource = LogPrefix + zsSource; if (!EventLog.SourceExists(zsSource, LogMachine)) { EventSourceCreationData srcData = new EventSourceCreationData(zsSource, LogName); EventLog.CreateEventSource(srcData); } EventLog eLog = null; try { eLog = new EventLog(zsModule, LogMachine, zsSource); eLog.WriteEntry(zsMsg, eType, 100); } finally { if (eLog != null) { eLog.Dispose(); } } } catch { if (!EventLog.SourceExists(LogPrefix, LogMachine)) { EventSourceCreationData srcData = new EventSourceCreationData(LogPrefix, LogName); EventLog.CreateEventSource(srcData); } EventLog eLog = new EventLog(LogName, LogMachine, LogPrefix); eLog.WriteEntry(@"Error trying to write to the log", EventLogEntryType.Error, 100); eLog.Dispose(); } }
/// <summary> /// Construct a sink posting to the Windows event log, creating the specified <paramref name="source"/> if it does not exist. /// </summary> /// <param name="source">The source name by which the application is registered on the local computer. </param> /// <param name="logName">The name of the log the source's entries are written to. Possible values include Application, System, or a custom event log.</param> /// <param name="textFormatter">Supplies culture-specific formatting information, or null.</param> /// <param name="machineName">The name of the machine hosting the event log written to.</param> public EventLogSink(string source, string logName, ITextFormatter textFormatter, string machineName) { if (source == null) { throw new ArgumentNullException("source"); } if (textFormatter == null) { throw new ArgumentNullException("textFormatter"); } _textFormatter = textFormatter; _source = source; var sourceData = new EventSourceCreationData(source, logName) { MachineName = machineName }; if (!System.Diagnostics.EventLog.SourceExists(source, machineName)) { System.Diagnostics.EventLog.CreateEventSource(sourceData); } }
private static void SendToActionLog(string eventMessage, EventSourceCreationData source, string strGat) { SendToActionLog(eventMessage, 1000, EventLogEntryType.Error, _eventSource, strGat); }
// ---------------------------------------------------------------------------------------- /// <!-- A --> /// <summary> /// Provides a breakpoint in development and throws an exception in production /// </summary> /// <param name="e">exception</param> /// <param name="actions">bug action</param> /// <returns>The id in the database if sent to the database</returns> public static Guid A(Exception ex, Endeme actions, EventSourceCreationData eventSource , GuiActionTrace gat) { if (_exceptionAct == null) { FillExceptionAct(); } // -------------------------------------------------------------------------- // Handle missing exception actions with a default Squawk-Log-Pause // -------------------------------------------------------------------------- if (_actions == null) { _actions = "" + Squawk + EventLog + Pauses; } if (actions == null) { actions = _actions; } // -------------------------------------------------------------------------- // Handle missing event log operational data by complaining // -------------------------------------------------------------------------- if (eventSource == null) { throw new NoNullAllowedException("EventSourceCreationData is null!" + "\r\n" + " You may have to add code something like this before running Throw:" + "\r\n" + " Throw.EventSourceBuild(\"MyProj\", \"MyProLog\");" ); } Guid guid = Guid.Empty; string strGat = ""; // -------------------------------------------------------------------------- // Prepare message text // -------------------------------------------------------------------------- string msg = ""; if (ex.InnerException != null) { msg = ex.InnerException.GetType().ToString() + "\r\n" + ex.InnerException.Message + "\r\n" + "\r\n" + ex.Message; } else { msg = ex.GetType().ToString() + " - " + ex.Message; } // -------------------------------------------------------------------------- // Determine action level // -------------------------------------------------------------------------- //int idx = actions.ToString().IndexOf('L'); //if (idx < 0) idx = 11; //int actionLevel; //if (idx >= 0) actionLevel = 22 - idx; //else actionLevel = 20; // default action level, action level is a callable/programmable cutoff point //// N is a mandatory cutoff point // -------------------------------------------------------------------------- // This is how to do it with an endeme // -------------------------------------------------------------------------- if (msg != _lastMessage && // don't keep spewing out the same messages msg != _prevMessage && !Regex.IsMatch(msg, "Deadlock victim", RegexOptions.IgnoreCase)) // I don't want to hear about deadlock victims { char[] act = actions.ToCharArray(); bool run = true; for (int i = 0; run && i < act.Length; ++i) { switch (act[i]) { //case DataLog: guid = SendToDatabase("CodeWhite", msg, strGat); break; case EventLog: SendToActionLog(msg, eventSource, strGat); break; case Ignore: break; case Email: break; case None: run = false; break; case Pauses: Pause(); break; // set a breakpoint here case Squawk: MessageBox.Show(msg); break; case Throws: throw ex; // turn this on in production and make sure it's handled } } } _prevMessage = _lastMessage; _lastMessage = msg; return(guid); }
private bool Initialize(string sourceName, string logName) { if (string.IsNullOrEmpty(sourceName) || string.IsNullOrEmpty(logName)) return false; try { EventSourceCreationData eventSourceCreationData = new EventSourceCreationData(sourceName, logName); if (!System.Diagnostics.EventLog.SourceExists(sourceName)) System.Diagnostics.EventLog.CreateEventSource(eventSourceCreationData); _EventLog = new System.Diagnostics.EventLog("Application", ".", sourceName); return true; } catch (Exception x) { XLogger.Error(x.ToString()); Console.WriteLine("XLogger.EventLog.Initialize ... Exception: " + x); return false; } }
protected override void BeginProcessing() { string str; string[] strArrays = this._computerName; for (int i = 0; i < (int)strArrays.Length; i++) { string str1 = strArrays[i]; if (str1.Equals("localhost", StringComparison.CurrentCultureIgnoreCase) || str1.Equals(".", StringComparison.OrdinalIgnoreCase)) { str = "localhost"; } else { str = str1; } try { string[] strArrays1 = this._source; for (int j = 0; j < (int)strArrays1.Length; j++) { string str2 = strArrays1[j]; if (EventLog.SourceExists(str2, str1)) { object[] objArray = new object[3]; objArray[1] = str; objArray[2] = str2; ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.SourceExistInComp, objArray)), null, ErrorCategory.InvalidOperation, null); base.WriteError(errorRecord); } else { EventSourceCreationData eventSourceCreationDatum = new EventSourceCreationData(str2, this._logName); eventSourceCreationDatum.MachineName = str1; if (!string.IsNullOrEmpty(this._messageResourceFile)) { eventSourceCreationDatum.MessageResourceFile = this._messageResourceFile; } if (!string.IsNullOrEmpty(this._parameterResourceFile)) { eventSourceCreationDatum.ParameterResourceFile = this._parameterResourceFile; } if (!string.IsNullOrEmpty(this._categoryResourceFile)) { eventSourceCreationDatum.CategoryResourceFile = this._categoryResourceFile; } EventLog.CreateEventSource(eventSourceCreationDatum); } } } catch (InvalidOperationException invalidOperationException1) { InvalidOperationException invalidOperationException = invalidOperationException1; this.WriteNonTerminatingError(invalidOperationException, EventlogResources.PermissionDenied, "PermissionDenied", ErrorCategory.PermissionDenied, this._logName, str, null, null); } catch (ArgumentException argumentException1) { ArgumentException argumentException = argumentException1; ErrorRecord errorRecord1 = new ErrorRecord(argumentException, "NewEventlogException", ErrorCategory.InvalidArgument, null); base.WriteError(errorRecord1); } catch (SecurityException securityException1) { SecurityException securityException = securityException1; this.WriteNonTerminatingError(securityException, EventlogResources.AccessIsDenied, "AccessIsDenied", ErrorCategory.InvalidOperation, null, null, null, null); } } }
static void Main(string[] args) { //<Snippet2> EventSourceCreationData mySourceData = new EventSourceCreationData("", ""); bool registerSource = true; // Process input parameters. if (args.Length > 0) { // Require at least the source name. mySourceData.Source = args[0]; if (args.Length > 1) { mySourceData.LogName = args[1]; } if (args.Length > 2) { mySourceData.MachineName = args[2]; } if ((args.Length > 3) && (args[3].Length > 0)) { mySourceData.MessageResourceFile = args[3]; } } else { // Display a syntax help message. Console.WriteLine("Input:"); Console.WriteLine(" source [event log] [machine name] [resource file]"); registerSource = false; } // Set defaults for parameters missing input. if (mySourceData.MachineName.Length == 0) { // Default to the local computer. mySourceData.MachineName = "."; } if (mySourceData.LogName.Length == 0) { // Default to the Application log. mySourceData.LogName = "Application"; } //</Snippet2> // Determine if the source exists on the specified computer. if (!EventLog.SourceExists(mySourceData.Source, mySourceData.MachineName)) { // The source does not exist. // Verify that the message file exists // and the event log is local. if ((mySourceData.MessageResourceFile != null) && (mySourceData.MessageResourceFile.Length > 0)) { if (mySourceData.MachineName == ".") { if (!System.IO.File.Exists(mySourceData.MessageResourceFile)) { Console.WriteLine("File {0} not found - message file not set for source.", mySourceData.MessageResourceFile); registerSource = false; } } else { // For simplicity, do not allow setting the message // file for a remote event log. To set the message // for a remote event log, and for source registration, // the file path should be specified with system-wide // environment variables that are valid on the remote // computer, such as // "%SystemRoot%\system32\myresource.dll". Console.WriteLine("Message resource file ignored for remote event log."); registerSource = false; } } } else { // Do not register the source, it already exists. registerSource = false; // Get the event log corresponding to the existing source. string sourceLog; sourceLog = EventLog.LogNameFromSourceName(mySourceData.Source, mySourceData.MachineName); // Determine if the event source is registered for the // specified log. if (sourceLog.ToUpper(CultureInfo.InvariantCulture) != mySourceData.LogName.ToUpper(CultureInfo.InvariantCulture)) { // An existing source is registered // to write to a different event log. Console.WriteLine("Warning: source {0} is already registered to write to event log {1}", mySourceData.Source, sourceLog); } else { // The source is already registered // to write to the specified event log. Console.WriteLine("Source {0} already registered to write to event log {1}", mySourceData.Source, sourceLog); } } if (registerSource) { // Register the new event source for the specified event log. Console.WriteLine("Registering new source {0} for event log {1}.", mySourceData.Source, mySourceData.LogName); EventLog.CreateEventSource(mySourceData); Console.WriteLine("Event source was registered successfully!"); } }
/// <summary> /// Establishes the specified source name as a valid event source for writing entries to a log on the specified computer. This method can also be used to create a new custom log on the specified computer. /// </summary> /// <param name="eventSourceName">The source by which the application is registered on the specified computer. </param> /// <param name="logName">The name of the log the source's entries are written to. Possible values include Application, System, or a custom event log. If you do not specify a value, logName defaults to Application. </param> /// <param name="machineName">The name of the computer to register this event source with, or "." for the local computer. </param> public static void CreateEventSource(string eventSourceName, string logName, string machineName) { EventSourceCreationData eventSourceData = new EventSourceCreationData(eventSourceName, logName); eventSourceData.MachineName = machineName; EventLog.CreateEventSource(eventSourceData); }
/// <inheritdoc /> public void CreateEventSource(EventSourceCreationData sourceData) => CreateEventSourceFunction(sourceData);
private void Install() { progressInstall.Style = ProgressBarStyle.Continuous; btClose.Enabled = false; gbSelectVersionToInstall.Enabled = false; gbInstallStatus.Enabled = true; Refresh(); // ########################################### // ### IS Exchange version supported? ### // ########################################### string agentExchangeVersionPath = ""; foreach (KeyValuePair <string, string> entry in Constants.DkimSignerVersionDirectory) { if (exchangeVersion.StartsWith(entry.Key)) { agentExchangeVersionPath = entry.Value; break; } } if (agentExchangeVersionPath == "") { MessageBox.Show(this, "Your Microsoft Exchange version isn't supported by the DKIM agent: " + exchangeVersion, "Version not supported", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { lbDownloadFiles.Enabled = true; } // path which is the base for copying the files. Should be the root of the downloaded .zip file. string extractPath; if (zipUrl != null) { // ########################################### // ### Download files ### // ########################################### string zipFile = ""; if (Uri.IsWellFormedUriString(zipUrl, UriKind.RelativeOrAbsolute)) { zipFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".zip"); DownloadProgressWindow oDpw = new DownloadProgressWindow(zipUrl, zipFile); try { if (oDpw.ShowDialog(this) == DialogResult.OK) { lbExtractFiles.Enabled = true; } } catch (Exception ex) { MessageBox.Show(this, "Couldn't initialize download progress window:\n" + ex.Message, "Error showing download progress", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { oDpw.Dispose(); } } else { if (File.Exists(zipUrl) && Path.GetExtension(zipUrl) == ".zip") { zipFile = zipUrl; lbExtractFiles.Enabled = true; } else { MessageBox.Show(this, "The URL or the path to the ZIP file is invalid. Please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } picDownloadFiles.Image = lbExtractFiles.Enabled ? statusImageList.Images[0] : statusImageList.Images[1]; progressInstall.Value = 1; Refresh(); // ########################################### // ### Extract files ### // ########################################### string zipDirName = Path.GetDirectoryName(zipFile); if (zipDirName == null) { MessageBox.Show(this, "Invaild Zip path", "Could not extract directory from zip path: " + zipFile, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } extractPath = Path.Combine(zipDirName, Path.GetFileNameWithoutExtension(zipFile)); if (lbExtractFiles.Enabled) { if (!Directory.Exists(extractPath)) { Directory.CreateDirectory(extractPath); } try { ZipFile.ExtractToDirectory(zipFile, extractPath); // copy root directory is one directory below extracted zip: string[] contents = Directory.GetDirectories(extractPath); if (contents.Length == 1) { extractPath = Path.Combine(extractPath, contents[0]); lbStopService.Enabled = true; } else { MessageBox.Show(this, "Downloaded .zip is invalid. Please try again.", "Invalid download", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { MessageBox.Show(this, ex.Message, "ZIP Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } picExtractFiles.Image = lbStopService.Enabled ? statusImageList.Images[0] : statusImageList.Images[1]; progressInstall.Value = 2; Refresh(); } else { // the files are already downloaded and in the same directory as this .exe file // the executable is within: \Src\Configuration.DkimSigner\bin\Release so we need to go up a few directories DirectoryInfo dir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory; if (dir == null) { MessageBox.Show(this, "Could not get directory info for: " + Assembly.GetExecutingAssembly().Location, "Directory error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } string[] expectedDirs = { "Release", "bin", "Configuration.DkimSigner", "Src" }; bool sanityFail = false; foreach (string str in expectedDirs) { if (dir == null || !dir.Name.Equals(str)) { sanityFail = true; break; } dir = dir.Parent; } if (dir == null) { sanityFail = true; } lbDownloadFiles.Enabled = !sanityFail; lbExtractFiles.Enabled = !sanityFail; lbStopService.Enabled = !sanityFail; if (sanityFail) { picDownloadFiles.Image = statusImageList.Images[1]; picExtractFiles.Image = statusImageList.Images[1]; Refresh(); MessageBox.Show(this, "Failed to determine copy root directory.\nThis executable is expected to be in the subpath: \\Src\\Configuration.DkimSigner\\bin\\Release", "ZIP Error", MessageBoxButtons.OK, MessageBoxIcon.Error); btClose.Enabled = true; return; } picDownloadFiles.Image = statusImageList.Images[0]; picExtractFiles.Image = statusImageList.Images[0]; progressInstall.Value = 2; Refresh(); extractPath = dir.FullName; } // ########################################### // ### Stop Microsoft Transport service ### // ########################################### if (lbStopService.Enabled) { if (transportService.GetStatus() != "Stopped") { transportServiceSuccessStatus = "Stopped"; transportService.Do(TransportServiceAction.Stop, delegate(string msg) { MessageBox.Show(msg, "Service error", MessageBoxButtons.OK, MessageBoxIcon.Error); }); lbCopyFiles.Enabled = transportServiceActionCompleted.WaitOne(); } else { lbCopyFiles.Enabled = true; } } picStopService.Image = lbCopyFiles.Enabled ? statusImageList.Images[0] : statusImageList.Images[1]; progressInstall.Value = 3; Refresh(); // ########################################### // ### Copy required files ### // ########################################### if (lbCopyFiles.Enabled) { List <string> filesToCopy = new List <string>(); filesToCopy.Add(Path.Combine(extractPath, @"Src\Configuration.DkimSigner\bin\Release")); filesToCopy.Add(Path.Combine(extractPath, Path.Combine(@"Src\Exchange.DkimSigner\bin\" + agentExchangeVersionPath))); // IF the directory "C:\Program Files\Exchange DkimSigner" doesn't exist, create it if (!Directory.Exists(Constants.DkimSignerPath)) { Directory.CreateDirectory(Constants.DkimSignerPath); } // Generate list of source files string[] sourceFiles = new string[0]; foreach (string sourcePath in filesToCopy) { string[] asTemp = Directory.GetFiles(sourcePath); Array.Resize(ref sourceFiles, sourceFiles.Length + asTemp.Length); Array.Copy(asTemp, 0, sourceFiles, sourceFiles.Length - asTemp.Length, asTemp.Length); } // Generate list of destinations files string[] destinationFiles = new string[sourceFiles.Length]; for (int i = 0; i < sourceFiles.Length; i++) { string sFile = Path.GetFileName(sourceFiles[i]); destinationFiles[i] = Path.Combine(Constants.DkimSignerPath, sFile); } bool bAnyOperationsAborted; bool bReturn = FileOperation.CopyFiles(Handle, sourceFiles, destinationFiles, true, "Copy files", out bAnyOperationsAborted); lbInstallAgent.Enabled = bReturn && !bAnyOperationsAborted; } // register Control Panel Applet if (lbInstallAgent.Enabled) { try { CplControl.Register(); } catch (Exception ex) { MessageBox.Show(this, "Could not create applet in control panel:\n" + ex.Message + "\nThe installation will be successful anyways but you won't be able to open the DKIM Configurator from the Control Panel", "Error creating applet", MessageBoxButtons.OK, MessageBoxIcon.Warning); } try { UninstallerRegistry.Register(); } catch (Exception ex) { MessageBox.Show(this, "Could not create uninstall entry in Program and Files:\n" + ex.Message + "\nThe installation will be successful anyways but you won't be able to open the DKIM Configurator from the Control Panel", "Error creating applet", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } picCopyFiles.Image = lbInstallAgent.Enabled ? statusImageList.Images[0] : statusImageList.Images[1]; progressInstall.Value = 4; Refresh(); // ############################################ // ### Install DKIM Signer Exchange Agent ### // ############################################ if (lbInstallAgent.Enabled) { try { // First make sure the following Registry key exists HKLM:\SYSTEM\CurrentControlSet\Services\EventLog\Application\Exchange DKIM if (EventLog.SourceExists(Constants.DkimSignerEventlogSource)) { // Make sure we recreate the event log source to fix messageResourceFile from versions previous to 2.0.0 RegistryKey key = Registry.LocalMachine.OpenSubKey(Constants.DkimSignerEventlogRegistry, false); if (key == null || key.GetValue("EventMessageFile") == null) { // Delete the event source for the custom event log EventLog.DeleteEventSource(Constants.DkimSignerEventlogSource); // Create a new event source for the custom event log EventSourceCreationData mySourceData = new EventSourceCreationData(Constants.DkimSignerEventlogSource, "Application"); mySourceData.MessageResourceFile = @"C:\Windows\Microsoft.NET\Framework\v4.0.30319\EventLogMessages.dll"; EventLog.CreateEventSource(mySourceData); } } else { // Create a new event source for the custom event log EventSourceCreationData mySourceData = new EventSourceCreationData(Constants.DkimSignerEventlogSource, "Application"); mySourceData.MessageResourceFile = @"C:\Windows\Microsoft.NET\Framework\v4.0.30319\EventLogMessages.dll"; EventLog.CreateEventSource(mySourceData); } // Install DKIM Transport Agent in Microsoft Exchange ExchangeServer.InstallDkimTransportAgent(); lbStartService.Enabled = true; } catch (ExchangeServerException ex) { MessageBox.Show(this, "Could not install DKIM Agent:\n" + ex.Message, "Error installing agent", MessageBoxButtons.OK, MessageBoxIcon.Error); } } picInstallAgent.Image = lbStartService.Enabled ? statusImageList.Images[0] : statusImageList.Images[1]; progressInstall.Value = 5; Refresh(); // ########################################### // ### Start Microsoft Transport service ### // ########################################### if (lbStartService.Enabled) { transportServiceSuccessStatus = "Running"; transportService.Do(TransportServiceAction.Start, delegate(string msg) { MessageBox.Show(msg, "Service error", MessageBoxButtons.OK, MessageBoxIcon.Error); }); picStartService.Image = transportServiceActionCompleted.WaitOne() ? statusImageList.Images[0] : statusImageList.Images[1]; } else { picStartService.Image = statusImageList.Images[1]; } progressInstall.Value = 6; Refresh(); btClose.Enabled = true; }
static void CreateEventSource(bool deletefirst) { if (deletefirst) { EventLog.DeleteEventSource("EventLogDemoApp"); EventLog.Delete("ProCSharpLog"); } string logName = "ProCSharpLog"; string sourceName = "EventLogDemoApp"; string resourceFile = @"c:\procsharp\TracingAndEvents\EventLogDemo\EventLogDemo\EventLogDemoMessages.dll"; if (!EventLog.SourceExists(sourceName)) { // string resourceFile = @"%SystemRoot%\System32\EventLogDemoMessages.dll"; if (!File.Exists(resourceFile)) { Console.WriteLine("Message resource file does not exist"); return; } EventSourceCreationData eventSource = new EventSourceCreationData(sourceName, logName); eventSource.CategoryResourceFile = resourceFile; eventSource.CategoryCount = 4; eventSource.MessageResourceFile = resourceFile; eventSource.ParameterResourceFile = resourceFile; EventLog.CreateEventSource(eventSource); } else { logName = EventLog.LogNameFromSourceName(sourceName, "."); } EventLog evLog = new EventLog(logName, ".", sourceName); evLog.RegisterDisplayName(resourceFile, 5001); using (var log = new EventLog(logName, ".", sourceName)) { EventInstance info = new EventInstance(1000, 4, EventLogEntryType.Information); log.WriteEvent(info); EventInstance info2 = new EventInstance(1001, 4, EventLogEntryType.Error); log.WriteEvent(info2, "avalon"); EventInstance info3 = new EventInstance(1002, 3, EventLogEntryType.Error); byte[] addionalInfo = { 1, 2, 3 }; log.WriteEvent(info3, addionalInfo); //log.WriteEntry("Message 1"); //log.WriteEntry("Message 2", EventLogEntryType.Warning); //log.WriteEntry("Message 3", EventLogEntryType.Information, 33); } //EventLog.WriteEntry("EventLogDemoApp", "Message 1"); //EventLog.WriteEntry("EventLogDemoApp", "Message 2", EventLogEntryType.Warning); //EventLog.WriteEntry("EventLogDemoApp", "Message 3", EventLogEntryType.Error, 37); }
/// <summary> /// Creates a new AucentCustomEventLogSource. Pass in your TaxonomyFileName (without extension) to create your log. /// </summary> public RivetCustomEventLogSource(string EventLogTitle, string EventSourceName, string TargetMachineName) { try { if (TargetMachineName == string.Empty || TargetMachineName == null) { TargetMachineName = Environment.MachineName; } eventLogName = EventLogTitle; if (EventLog.SourceExists(EventSourceName, TargetMachineName)) { // Are we dealing with the same log for the source? if (EventLogTitle.Trim() != EventLog.LogNameFromSourceName(EventSourceName, TargetMachineName).Trim()) { EventLog.DeleteEventSource(EventSourceName, TargetMachineName); } } // Create EventLog if needed if (!EventLog.Exists(EventLogTitle, TargetMachineName)) { if (EventLog.SourceExists(EventLogTitle, TargetMachineName)) { // If an event source exists in the name of the EventLog, we should remove the // event source try { EventLog.DeleteEventSource(EventLogTitle, TargetMachineName); } catch { // If we had an issue with deleting the EventSource because it matches some EventLog title, // we have no choice but to remove the EventLog alltogether! EventLog.Delete(EventLogTitle, TargetMachineName); } } EventSourceCreationData dataSource = new EventSourceCreationData(EventSourceName, EventLogTitle); dataSource.MachineName = TargetMachineName; EventLog.CreateEventSource(dataSource); } // Create the event source if it does not exist if (!EventLog.SourceExists(EventSourceName, TargetMachineName)) { EventSourceCreationData dataSource = new EventSourceCreationData(EventSourceName, EventLogTitle); dataSource.MachineName = TargetMachineName; EventLog.CreateEventSource(dataSource); } if (!eventLogsUpdated.Contains(EventLogTitle)) { EventLog myLog = new EventLog(EventLogTitle, TargetMachineName); if (myLog.OverflowAction != OverflowAction.OverwriteAsNeeded) { myLog.ModifyOverflowPolicy(OverflowAction.OverwriteAsNeeded, 0); } eventLogsUpdated.Add(EventLogTitle); } } catch (System.Exception ex) { string msg = ex.Message; } }
static void Main(string[] args) { SQLDatabaseAccess SQLDBA = new SQLDatabaseAccess(); SqlDataReader sqlDR; int maxrange; //sFilePath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); sFilePath = @"C:\WebSites\www.beatgraphs.com\"; /* EVENT LOGGING */ string sSource = "BGraphs"; string sLog = "BGraphsLog"; EventSourceCreationData escdSource = new EventSourceCreationData(sSource, sLog); escdSource.MachineName = "."; eLog = new EventLog(); if (!EventLog.SourceExists(sSource, escdSource.MachineName)) { EventLog.CreateEventSource(escdSource); } eLog.Source = sSource; eLog.WriteEntry("Runner job started.", EventLogEntryType.Information, 0, (short)0); SQLDBA.Open(); SQLDBA.ExecuteSqlSP("Select_RegSeason_Graphs", out sqlDR); if (sqlDR.HasRows) { while (sqlDR.Read()) { league = SQLDBA.sqlGet(sqlDR, "League"); year = SQLDBA.sqlGet(sqlDR, "Year"); maxrange = int.Parse(SQLDBA.sqlGet(sqlDR, "LastWeek")); if (league == "MLB") { if (strSeasonMLB == "") { strSeasonMLB = year; } else if (strSeasonMLB != year) { continue; } } if (league == "NBA") { if (strSeasonNBA == "") { strSeasonNBA = year; } else if (strSeasonNBA != year) { continue; } } if (league == "NFL") { if (strSeasonNFL == "") { strSeasonNFL = year; } else if (strSeasonNFL != year) { continue; } } if (league == "NHL") { if (strSeasonNHL == "") { strSeasonNHL = year; } else if (strSeasonNHL != year) { continue; } } if (league == "NCAAF") { if (strSeasonNCAAF == "") { strSeasonNCAAF = year; } else if (strSeasonNCAAF != year) { continue; } } //if (league == "NCAAF") //Use this to exclude a league or run a specific league from the run // continue; //for (int i = 1; i <= maxrange; i++) //Use this to run the entire season for (int i = maxrange; i <= maxrange; i++) //Use this to run just the latest week, this is for everyday runs. { Process pBuilder = new Process(); pBuilder.StartInfo.FileName = @"C:\WebSites\www.beatgraphs.com\Code\BGBuilder\BGBuilder\bin\Debug\BGBuilder.exe"; pBuilder.StartInfo.Arguments = "-l " + league + " -s " + year + " -r " + i + " -m S"; Console.WriteLine(@"C:\WebSites\www.beatgraphs.com\Code\BGBuilder\BGBuilder\bin\Debug\BGBuilder.exe -l " + league + " -s " + year + " -r " + i + " -m S"); try { pBuilder.StartInfo.RedirectStandardOutput = true; pBuilder.StartInfo.UseShellExecute = false; pBuilder.StartInfo.CreateNoWindow = true; pBuilder.Start(); pBuilder.WaitForExit(); } catch (Exception ex) { Console.WriteLine("Failed: " + ex.Message); eLog.WriteEntry("Builder job failed (Standard): " + ex.Message, EventLogEntryType.Error, 0, (short)0); } pBuilder.StartInfo.Arguments = "-l " + league + " -s " + year + " -r " + i + " -m I"; Console.WriteLine(@"C:\WebSites\www.beatgraphs.com\Code\BGBuilder\BGBuilder\bin\Debug\BGBuilder.exe -l " + league + " -s " + year + " -r " + i + " -m I"); try { pBuilder.Start(); pBuilder.WaitForExit(); } catch (Exception ex) { Console.WriteLine("Failed: " + ex.Message); eLog.WriteEntry("Builder job failed (Iterative): " + ex.Message, EventLogEntryType.Error, 0, (short)0); } pBuilder.StartInfo.Arguments = "-l " + league + " -s " + year + " -r " + i + " -m W"; Console.WriteLine(@"C:\WebSites\www.beatgraphs.com\Code\BGBuilder\BGBuilder\bin\Debug\BGBuilder.exe -l " + league + " -s " + year + " -r " + i + " -m W"); try { pBuilder.Start(); pBuilder.WaitForExit(); } catch (Exception ex) { Console.WriteLine("Failed: " + ex.Message); eLog.WriteEntry("Builder job failed (Weighted): " + ex.Message, EventLogEntryType.Error, 0, (short)0); } } } } SQLDBA.Close(); sqlDR.Close(); SQLDBA.Dispose(); sqlDR.Dispose(); runPlayoffs(); listLeagues(); printFooter(); uploadTop5s(); eLog.WriteEntry("RUNNER COMPLETED.", EventLogEntryType.Information, 0, (short)0); }
public static void CreateEventSource(EventSourceCreationData sourceData) {}
void btnRefresh_Click(object sender, EventArgs e) { string machineName; // Если IP не указан, то используем локальный адрес if (String.IsNullOrEmpty(tbServiceIP.Text)) { machineName = "127.0.0.1"; } else { // Иначе берем тот, что указан machineName = tbServiceIP.Text; } // Получаем DNS из IP адреса string hostName = Dns.GetHostEntry(machineName).HostName.Split('.')[0]; EventSourceCreationData creationData = new EventSourceCreationData(serviceName, serviceName); creationData.MachineName = hostName; // Если журнал существует if (EventLog.SourceExists(serviceName, hostName)) { // Считываем источник журнала string logName = EventLog.LogNameFromSourceName(serviceName, hostName); // Если не совпадает с нужным if (logName != serviceName) { // Удаляем источник EventLog.DeleteEventSource(serviceName, hostName); // Создаем нужный источник EventLog.CreateEventSource(creationData); } } else { // Создаем журнал EventLog.CreateEventSource(creationData); } // Имя журнала events.Log = serviceName; // Имя источника events.Source = serviceName; // Имя компьютера events.MachineName = hostName; try { // Заполняем таблицу для отображения if (events.Entries.Count > 0) { // Если таблица пустая, то привязываем ее к журналу if (dgEvents.ItemsSource == null) { dgEvents.ItemsSource = events.Entries; } // Обновляем записи CollectionViewSource.GetDefaultView(dgEvents.ItemsSource).Refresh(); // Очищаем описание сортировки dgEvents.Items.SortDescriptions.Clear(); // Созадем описание сортировки dgEvents.Items.SortDescriptions.Add(new SortDescription(dgEvents.Columns[0].SortMemberPath, ListSortDirection.Descending)); // Очищаем сортировку всех столбцов foreach (var col in dgEvents.Columns) { col.SortDirection = null; } // Задаем сортировку времени по убыванию (последняя запись вверху) dgEvents.Columns[0].SortDirection = ListSortDirection.Descending; // Обновляем записи dgEvents.Items.Refresh(); } } catch (Exception ex) { System.Windows.MessageBox.Show(ex.Message); } }
public static void CreateEventSource(EventSourceCreationData sourceData) { }
private void UpdateEventLogSource() { if (!_needEventLogSourceUpdate) { return; } lock (this) { _operational = false; // if we throw anywhere, we remain non-operational try { if (!_needEventLogSourceUpdate) { return; } if (EventLog.SourceExists(_sourceName, _machineName)) { string currentLogName = EventLog.LogNameFromSourceName(_sourceName, _machineName); if (currentLogName != _logName) { // re-create the association between Log and Source EventLog.DeleteEventSource(_sourceName, _machineName); #if DOTNET_2_0 EventSourceCreationData escd = new EventSourceCreationData(_sourceName, _logName); escd.MachineName = _machineName; EventLog.CreateEventSource(escd); #else EventLog.CreateEventSource(_sourceName, _logName, _machineName); #endif } else { // ok, Source registered and associated with the correct Log } } else { #if DOTNET_2_0 EventSourceCreationData escd = new EventSourceCreationData(_sourceName, _logName); escd.MachineName = _machineName; EventLog.CreateEventSource(escd); #else // source doesn't exist, register it. EventLog.CreateEventSource(_sourceName, _logName, _machineName); #endif } // mark the configuration as operational _operational = true; } catch (Exception ex) { InternalLogger.Error("Error when connecting to EventLog: {0}", ex); } finally { _needEventLogSourceUpdate = false; } } }
public override void RecordMessage(AlertRaised alertRaised) { string lastStep = ""; try { EventLogNotifierConfig currentConfig = (EventLogNotifierConfig)AgentConfig; if (currentConfig.MachineName.Length == 0) { throw new Exception("Computer name not specified!"); } if (currentConfig.EventSource.Length == 0) { throw new Exception("Event source not specified!"); } string currentEventSource = currentConfig.EventSource; string collectorName = "QuickMon Global Alert"; string collectorAgents = "None"; string oldState = "N/A"; string newState = "N/A"; string detailMessage = alertRaised.MessageRaw; string viaHost = "N/A"; if (alertRaised.RaisedFor != null) { collectorName = alertRaised.RaisedFor.Name; collectorAgents = string.Format("{0} agent(s)", alertRaised.RaisedFor.CollectorAgents.Count); if (alertRaised.RaisedFor.CollectorAgents.Count > 0) { collectorAgents += " {"; alertRaised.RaisedFor.CollectorAgents.ForEach(ca => collectorAgents += ca.AgentClassDisplayName + ","); collectorAgents = collectorAgents.TrimEnd(',') + "}"; } oldState = Enum.GetName(typeof(CollectorState), alertRaised.RaisedFor.PreviousState.State); newState = Enum.GetName(typeof(CollectorState), alertRaised.RaisedFor.CurrentState.State); if (alertRaised.RaisedFor.OverrideRemoteAgentHost) { viaHost = string.Format("{0}:{1}", alertRaised.RaisedFor.OverrideRemoteAgentHostAddress, alertRaised.RaisedFor.OverrideRemoteAgentHostPort); } else if (alertRaised.RaisedFor.EnableRemoteExecute) { viaHost = string.Format("{0}:{1}", alertRaised.RaisedFor.RemoteAgentHostAddress, alertRaised.RaisedFor.RemoteAgentHostPort); } } currentEventSource = currentConfig.EventSource .Replace("%CollectorName%", collectorName); lastStep = "Test if source exists"; string logName = currentConfig.EventLogName; if (!EventLog.SourceExists(currentEventSource, currentConfig.MachineName)) { lastStep = "Attempt to create event source " + currentEventSource; EventSourceCreationData escd = new EventSourceCreationData(currentEventSource, logName); escd.MachineName = currentConfig.MachineName; EventLog.CreateEventSource(escd); } try { //in case some admin created the source in a different event log logName = EventLog.LogNameFromSourceName(currentEventSource, currentConfig.MachineName); } catch { } lastStep = "Opening event log on " + currentConfig.MachineName; EventLog outputLog = new EventLog(logName, currentConfig.MachineName, currentEventSource); EventLogEntryType eventLogEntryType = (alertRaised.Level == AlertLevel.Info || alertRaised.Level == AlertLevel.Debug) ? EventLogEntryType.Information : alertRaised.Level == AlertLevel.Warning ? EventLogEntryType.Warning : EventLogEntryType.Error; int eventID = (alertRaised.Level == AlertLevel.Info || alertRaised.Level == AlertLevel.Debug) ? currentConfig.SuccessEventID : alertRaised.Level == AlertLevel.Warning ? currentConfig.WarningEventID : currentConfig.ErrorEventID; lastStep = "Generate output stream"; string outputStr = string.Format("Time: {0}\r\nAlert level: {1}\r\nCollector: {2}\r\nAgents: {3}\r\nOld state: {4}\r\nCurrent state: {5}\r\nVia host: {6}\r\nDetails: {7}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Enum.GetName(typeof(AlertLevel), alertRaised.Level), collectorName, collectorAgents, oldState, newState, viaHost, detailMessage); lastStep = "Write the event log entry"; outputLog.WriteEntry(outputStr, eventLogEntryType, eventID); } catch (Exception ex) { throw new Exception("Error recording message in Event log notifier\r\nLast step: " + lastStep, ex); } finally { //eventLogWriteMutex.ReleaseMutex(); } }
public static void InitialiseLUM() { if (File.Exists(ConfigFilePath)) { if (!EventLog.SourceExists(LogUploadManager.strSource, LogUploadManager.strMachine)) { EventSourceCreationData eventData = new EventSourceCreationData(LogUploadManager.strSource, LogUploadManager.strLog); EventLog.CreateEventSource(eventData); } EventLog.WriteEntry(LogUploadManager.strSource, "Config file found at:" + ConfigFilePath, EventLogEntryType.Information, 1987); try { // Read configuration and start work XDocument doc = XDocument.Load(ConfigFilePath); Dictionary <string, string> keyValues = doc.Descendants("add").ToDictionary(x => x.Attribute("key").Value, x => x.Attribute("value").Value); strContainer = keyValues["Container"]; strStorageAccName = keyValues["StorageAccName"]; strStorageAccKey = keyValues["StorageAccKey"]; if (int.TryParse(keyValues["UploadFrequencySeconds"], out UploadFrequencyInSeconds)) { // Update upload interval } else { if (!EventLog.SourceExists(LogUploadManager.strSource, LogUploadManager.strMachine)) { EventSourceCreationData eventData = new EventSourceCreationData(LogUploadManager.strSource, LogUploadManager.strLog); EventLog.CreateEventSource(eventData); } EventLog.WriteEntry(LogUploadManager.strSource, "NE Portal Log Upload Manager has encountered an error:" + Environment.NewLine + "Upload frequency value was not in correct format. Please check if " + ConfigFilePath + " has correct values. Then restart the 'NEPortalLogUploader' service.", EventLogEntryType.Error, 1983); } try { uploadTimer = new System.Timers.Timer(); uploadTimer.Interval = (int)(TimeSpan.FromSeconds(UploadFrequencyInSeconds).TotalMilliseconds); uploadTimer.Elapsed += new System.Timers.ElapsedEventHandler(uploadTimer_Tick); uploadTimer.AutoReset = false; uploadTimer.Start(); UploadsCycleActive = true; } catch (Exception ex) { EventLog.WriteEntry(LogUploadManager.strSource, "Error while setting Timer. Setting up Timer: " + ex.Message, EventLogEntryType.Error, 1983); } } catch (Exception ex) { if (!EventLog.SourceExists(LogUploadManager.strSource, LogUploadManager.strMachine)) { EventSourceCreationData eventData = new EventSourceCreationData(LogUploadManager.strSource, LogUploadManager.strLog); EventLog.CreateEventSource(eventData); } EventLog.WriteEntry(LogUploadManager.strSource, "NE Portal Log Upload Manager has encountered an error while configuring the upload settings:" + Environment.NewLine + ex.Message, EventLogEntryType.Error, 1983); } } else { EventLog.WriteEntry(LogUploadManager.strSource, "Missing configuration file at: " + ConfigFilePath + Environment.NewLine + "Place the configuration file at this path and Restart 'NEPortalLogUploader' service for successful uploading of log files.", EventLogEntryType.Error, 1983); } }
static void Main(string[] args) { #region tracesource ////TraceSource source1 = new TraceSource("APP-SQ", SourceLevels.Error|SourceLevels.Warning); ////TraceSource source1 = new TraceSource(ConfigurationManager.AppSettings["MyTraceSource"]); ////跟踪源名称在配置文件中描述 //TraceSource source1 = new TraceSource("MyTraceSource"); //source1.Switch = new SourceSwitch("MySourceSwitch", "Warning"); //XmlWriterTraceListener listener = new XmlWriterTraceListener("xmlDemo.xml"); ////listener.TraceOutputOptions = TraceOptions.DateTime | TraceOptions.LogicalOperationStack | TraceOptions.ProcessId | TraceOptions.Timestamp; //source1.Listeners.Add(listener); //source1.TraceInformation("普通信息"); //source1.TraceEvent(TraceEventType.Error, 33,"发生错误"); //source1.TraceData(TraceEventType.Information, 22, "ddw"); //source1.Close(); #endregion #region log //EventLog.Delete("SQ日志文件"); //EventLog.DeleteEventSource("SQ应用程序源"); //if (!EventLog.SourceExists("SQ应用程序源")) //{ // //EventSourceCreationData eventData = new EventSourceCreationData("SQ应用程序源", "SQ日志文件"); // EventSourceCreationData eventData = new EventSourceCreationData("SQ应用程序源", "SQ日志文件"); // //eventData.LogName = "SQ日志文件"; // EventLog.CreateEventSource(eventData); //} //EventLog.WriteEntry("SQ应用程序源", "错误", EventLogEntryType.Error, 33); //using (EventLog log = new EventLog("SQ日志文件",".","SQ应用程序源")) //{ // log.WriteEntry("消息1"); // log.WriteEntry("消息2:警告", EventLogEntryType.Warning); // log.WriteEntry("消息3:错误", EventLogEntryType.Error, 33334); //} //if (EventLog.Exists("SQ")) //{ // EventLog.Delete("SQ"); // //EventLog.DeleteEventSource("SQ"); //} //EventLog.DeleteEventSource("EventAppLog", "."); #endregion //if (EventLog.Exists("SQ日志文件")) //{ // EventLog.Delete("SQ日志文件"); //} //if (EventLog.SourceExists("SQ应用程序源")) //{ // EventLog.DeleteEventSource("SQ应用程序源"); //} if (!EventLog.Exists("SQ日志文件")) { EventSourceCreationData sourceData = new EventSourceCreationData("SQ应用程序源", "SQ日志文件"); EventLog.CreateEventSource(sourceData); } using (EventLog log = new EventLog("SQ日志文件", ".", "SQ应用程序源")) { //log.WriteEvent(new EventInstance(10,2, log.WriteEntry("消息1"); log.WriteEntry("消息2:警告", EventLogEntryType.Warning); log.WriteEntry("消息3:错误", EventLogEntryType.Error, 33334); } Console.WriteLine("Over!"); Console.ReadLine(); }
/// <summary> /// Construct a sink posting to the Windows event log, creating the specified <paramref name="source"/> if it does not exist. /// </summary> /// <param name="source">The source name by which the application is registered on the local computer. </param> /// <param name="logName">The name of the log the source's entries are written to. Possible values include Application, System, or a custom event log.</param> /// <param name="textFormatter">Supplies culture-specific formatting information, or null.</param> /// <param name="machineName">The name of the machine hosting the event log written to.</param> /// <param name="manageEventSource">If false does not check/create event source. Defaults to true i.e. allow sink to manage event source creation</param> public EventLogSink(string source, string logName, ITextFormatter textFormatter, string machineName, bool manageEventSource) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (textFormatter == null) { throw new ArgumentNullException(nameof(textFormatter)); } //The source is limitted in length and allowed chars //see: https://msdn.microsoft.com/en-us/library/e29k5ebc%28v=vs.110%29.aspx source = source.Substring(0, Math.Min(source.Length, 212)); source = source.Replace("<", "_"); source = source.Replace(">", "_"); _textFormatter = textFormatter; _logName = logName; if (string.IsNullOrWhiteSpace(_logName)) { _logName = APPLICATION_LOG; } _log = new System.Diagnostics.EventLog(_logName); if (manageEventSource) { var sourceData = new EventSourceCreationData(source, _logName) { MachineName = machineName }; Action logSourceMoved = () => { }; var sourceExistsInAnyLog = System.Diagnostics.EventLog.SourceExists(source, machineName); if (sourceExistsInAnyLog) { var existingLogWithSourceName = System.Diagnostics.EventLog.LogNameFromSourceName(source, machineName); if (!string.IsNullOrWhiteSpace(existingLogWithSourceName)) { //remove it from previous log so we can associated it with the current logName System.Diagnostics.EventLog.DeleteEventSource(source, machineName); //stash a reference to this guy so we can add a log entry noting the logs your looking for are in the //log previously associated with "source" //we don't log here in case creating the event source fails (if the create failed, an entry here would be misleading) logSourceMoved = () => { var metaSource = $"serilog-{_logName}"; if (!System.Diagnostics.EventLog.SourceExists(metaSource, machineName)) { System.Diagnostics.EventLog.CreateEventSource(new EventSourceCreationData(metaSource, _logName) { MachineName = machineName }); } _log.Source = metaSource; _log.WriteEntry( message: $"Event source {source} was previously registered in log {existingLogWithSourceName}. " + $"The source has been registered with this log, {_logName}, however a computer restart may be required " + $"before event logs will appear in {_logName} with source {source}. Until then, messages may be logged to {existingLogWithSourceName}.", type: EventLogEntryType.Warning, eventID: (int)LogEventLevel.Warning); }; } } else { System.Diagnostics.EventLog.CreateEventSource(sourceData); } logSourceMoved(); } _log.Source = source; }