/// <summary> /// Create log in Event log /// </summary> /// <param name="message">The message to be logged into the event log</param> /// <param name="logType">contains information, warning and error</param> private void Log(string message, EventLogEntryType logType) { System.Diagnostics.EventLog SQLEventLog = new System.Diagnostics.EventLog(); try { if (!System.Diagnostics.EventLog.SourceExists(_logSource)) { this.CreateLog(_logSource); } SQLEventLog.Source = _logSource; SQLEventLog.WriteEntry(Convert.ToString(_logName) + ": " + Convert.ToString(message), logType); } catch (Exception ex) { SQLEventLog.Source = _logSource; SQLEventLog.WriteEntry(Convert.ToString("INFORMATION: ") + Convert.ToString(ex.Message), EventLogEntryType.Error); } finally { SQLEventLog.Dispose(); SQLEventLog = null; } }
public void Stop() { try { if (!_started) { return; } _cancel.Cancel(); _eventLog.EnableRaisingEvents = false; // This would be a little racy if start and stop were ever called on different threads, but // this isn't done, currently. _retroactiveLoadingTask?.Wait(); _eventLog.Close(); _eventLog.Dispose(); Serilog.Log.Information("Listener stopped"); } catch (Exception ex) { Serilog.Log.Error(ex, "Failed to stop listener"); } }
protected override void Dispose(bool disposing) { if (disposing) { event_log.Dispose(); } }
/// <summary> /// Logs an error to the Windows event log /// </summary> /// <param name="eventLog">The event log</param> /// <param name="source">The source of the error</param> /// <param name="errorMessage">The error message</param> public static void LogError(string eventLog, string source, string errorMessage) { // Thread abort can occur because of cleanup code and we do not need to log this if (!errorMessage.Contains("Thread was being aborted")) { try { // Create an EventLog instance and assign its source. EventLog log = new EventLog(eventLog); log.Source = source; log.WriteEntry(errorMessage, EventLogEntryType.Error); log.Dispose(); log = null; } catch { // We do not want to stop processing if we cannot log to the event log, // we also do not want to re-throw an exception, because this will just cause an infinite loop } try { // Email the error to Support EmailError(errorMessage); } catch { // We do not want to stop processing if we cannot log to the event log, // we also do not want to re-throw an exception, because this will just cause an infinite loop } } }
// We only want this method exposed to code // in the same assembly. However, we might need to // change the scope if this class were in another // assembly. internal void LogError() { System.Diagnostics.EventLog e; e = new System.Diagnostics.EventLog("Application"); e.Source = this.AppSource; e.WriteEntry(this.Message, System.Diagnostics.EventLogEntryType.Error); e.Dispose(); }
/// <summary> /// Closes the log. /// </summary> /// <remarks> /// This will dispose of the underlying <see cref="System.Diagnostics.EventLog"/>. After calling this method, <see cref="Open"/> must be called before attempting to read or write to the log. /// </remarks> public override void Close() { if (_EventLog != null) { _EventLog.Dispose(); _EventLog = null; } _IsOpen = false; }
public static void WriteToEventLog(string strLogName, string strSource, string strErrDetail, string type, string methodsClass) { System.Diagnostics.EventLog SQLEventLog = new System.Diagnostics.EventLog(); int EventID = 0; try { if (!System.Diagnostics.EventLog.SourceExists(strLogName)) { CreateLog(strLogName); } SQLEventLog.Log = strLogName; if (!string.IsNullOrEmpty(methodsClass)) { SQLEventLog.Source = methodsClass; } else { SQLEventLog.Source = strLogName; } if (type == "Information") { SQLEventLog.WriteEntry(Convert.ToString(strSource) + Environment.NewLine + Convert.ToString(strErrDetail), EventLogEntryType.Information, EventID); } else { SQLEventLog.WriteEntry(Convert.ToString(strSource) + Environment.NewLine + Convert.ToString(strErrDetail), EventLogEntryType.Error, EventID); } } catch (Exception ex) { if (!string.IsNullOrEmpty(methodsClass)) { SQLEventLog.Source = methodsClass; } else { SQLEventLog.Source = "EpicorERPLogException"; } SQLEventLog.WriteEntry(Convert.ToString("INFORMATION: ") + Environment.NewLine + Convert.ToString(ex.Message), EventLogEntryType.Error); } finally { SQLEventLog.Dispose(); SQLEventLog = null; } }
public static void SqlExceptionHandling(SqlException sqlex, string strModule, string strMethod, string strMsg) { EventLog objEventLog = new EventLog(); string strApplicationName = "SLDDBLog"; objEventLog.Source = strApplicationName; objEventLog.Log = strApplicationName; objEventLog.WriteEntry(Environment.NewLine + "Date : " + DateTime.Now + Environment.NewLine + "Module Name : " + strModule + Environment.NewLine + "Method Name : " + strMethod + Environment.NewLine + "Exception Number : " + sqlex.ErrorCode + Environment.NewLine + "Exception Message : " + sqlex.Message + Environment.NewLine + "Additional Information : " + strMsg, EventLogEntryType.Error); objEventLog.Close(); objEventLog.Dispose(); }
/// Ghi vào EvenLog Windows /// </summary> private void WriteToEventLog(Exception objError) { //********************************************************************* //* Purpose:Writing error to the windows event log * //* Input parameters: * //* objError----Exception object * //* Returns : * //* nothing * //* ******************************************************************* System.Diagnostics.EventLog objEventLog = new System.Diagnostics.EventLog(); objEventLog.Source = "DataAccess Error ...."; objEventLog.WriteEntry(objError.Message.ToString()); objEventLog.Dispose(); }
/// <summary> /// Метод инициализации журнала событий Windows. /// </summary> public static void Init() { // Иницируем журнал событий Windows try { // Если не существует windows лога службы, то создаем его и назначаем по-умолчанию для записи if (!EventLog.SourceExists("SmartHouseService")) EventLog.CreateEventSource("SmartHouseService", "SmartHouseServiceLog"); // Иницируем журнал событий Windows _log = new EventLog(); _log.Source = "SmartHouseService"; _log.Log = "SmartHouseServiceLog"; _log.ModifyOverflowPolicy(OverflowAction.OverwriteAsNeeded, 30); } catch (Exception) { if (_log != null) _log.Dispose(); _log = null; } }
private static bool EventSourceExists(string source) { if (System.Diagnostics.EventLog.SourceExists(source)) { System.Diagnostics.EventLog evLog = new System.Diagnostics.EventLog { Source = source }; if (evLog.Log != ESightEventLogName) { System.Diagnostics.EventLog.DeleteEventSource(source); } evLog.Dispose(); } if (!System.Diagnostics.EventLog.SourceExists(source)) { System.Diagnostics.EventLog.CreateEventSource(source, ESightEventLogName); } return(System.Diagnostics.EventLog.SourceExists(source)); }
public void WriteEvent(string strMessage, EventLogEntryType type) { if (!EventLog.SourceExists(this._sourece)) EventLog.CreateEventSource(this._sourece, this._eventName); EventLog eventLog = new EventLog(); eventLog.Log = this._eventName; eventLog.Source = this._sourece; try { eventLog.WriteEntry(strMessage, type); } catch (Exception ex) { eventLog.Clear(); this.WriteEvent("日志文件已满,执行清除操作!", EventLogEntryType.Warning); eventLog.WriteEntry(strMessage, type); } finally { eventLog.Close(); eventLog.Dispose(); } }
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(); } }
public void ExceptionLoggingWorksAsExpected() { // --- Arrange var eventLog = new EventLog(SEEMPLEST_LOG2); const string TEST_EX = "This is a test exception"; const string TEST_INNER_EX = "This is an inner test exception"; // --- Act var innerEx = new InvalidOperationException(TEST_EX); var ex = new InvalidOperationException(TEST_INNER_EX, innerEx); WindowsEventLogger.Log<WithExceptionAttributes>("Message:", ex); // --- Assert var after = eventLog.Entries; var afterCount = after.Count; afterCount.ShouldEqual(1); var lastentry = after[after.Count - 1]; lastentry.Category.ShouldEqual("(0)"); lastentry.InstanceId.ShouldEqual(0); lastentry.Message.StartsWith("Message:").ShouldBeTrue(); lastentry.Source.ShouldEqual(SEEMPLEST_SOURCE); lastentry.EntryType.ShouldEqual(EventLogEntryType.Error); eventLog.Dispose(); }
public void WithTypeAttributeWorksAsExpected() { // --- Arrange var eventLog = new EventLog(SEEMPLEST_LOG2); // --- Act WindowsEventLogger.Log<WithTypeNameAttribute>("Message"); // --- Assert var after = eventLog.Entries; var afterCount = after.Count; afterCount.ShouldEqual(1); var lastentry = after[after.Count - 1]; lastentry.Category.ShouldEqual("(5)"); lastentry.InstanceId.ShouldEqual(3); lastentry.Message.ShouldEqual("Message"); lastentry.Source.ShouldEqual(SEEMPLEST_SOURCE); lastentry.EntryType.ShouldEqual(EventLogEntryType.Information); eventLog.Dispose(); }
public void WorksInParalell() { // --- Arrange var eventLog = new EventLog(SEEMPLEST_LOG2); // --- Act Parallel.For(0, 40, num => WindowsEventLogger.Log<WithStringNameAttribute>(String.Format("Message{0}", num))); // --- Assert var after = eventLog.Entries; var afterCount = after.Count; afterCount.ShouldEqual(40); var messagelist = new List<string>(); foreach (EventLogEntry lastentry in after) { lastentry.Category.ShouldEqual("(5)"); lastentry.InstanceId.ShouldEqual(3); messagelist.Add(lastentry.Message); lastentry.Source.ShouldEqual(SEEMPLEST_SOURCE); lastentry.EntryType.ShouldEqual(EventLogEntryType.Information); } for (int i = 0; i < 40; i++) { messagelist.Contains(String.Format("Message{0}", i)).ShouldBeTrue( String.Format("Message{0} was not found", i)); } eventLog.Dispose(); }
public void OnlyWithRequiredAttributesWorksAsExpected() { // --- Arrange var eventLog = new EventLog(SEEMPLEST_LOG2); // --- Act WindowsEventLogger.Log<WithOnlyRequiredAttributes>("Message"); // --- Assert var after = eventLog.Entries; var afterCount = after.Count; afterCount.ShouldEqual(1); var lastentry = after[after.Count - 1]; lastentry.Category.ShouldEqual("(0)"); lastentry.InstanceId.ShouldEqual(0); lastentry.Message.ShouldEqual("Message"); lastentry.Source.ShouldEqual(SEEMPLEST_SOURCE); lastentry.EntryType.ShouldEqual(EventLogEntryType.Warning); eventLog.Dispose(); }
public void WithInstancePrefixWorksAsExpected() { // --- Arrange var configSettings = new AppConfigurationSettings( typeof(AppConfigProvider), null, null, "TestInstancePrefix", "TestInstanceName"); AppConfigurationManager.Configure(configSettings); WindowsEventLogger.LogSourceMapper = new DefaultLogSourceNameMapper(); var eventLog = new EventLog(SEEMPLEST_LOG2); // --- Act WindowsEventLogger.Log<WithStringNameAttribute>("Message"); // --- Assert var after = eventLog.Entries; var afterCount = after.Count; afterCount.ShouldEqual(1); var lastentry = after[after.Count - 1]; lastentry.Category.ShouldEqual("(5)"); lastentry.InstanceId.ShouldEqual(3); lastentry.Message.ShouldEqual("Message"); lastentry.Source.ShouldEqual("TestInstancePrefix" + SEEMPLEST_SOURCE); lastentry.EntryType.ShouldEqual(EventLogEntryType.Information); eventLog.Dispose(); }
public void LogWithRedirectionWorksAsExpected() { // --- Arrange if (!Directory.Exists(LOG_ROOT)) { Directory.CreateDirectory(LOG_ROOT); } File.Delete(Path.Combine(LOG_ROOT, LOG_FILE)); var tracer = new FileTraceLogger(LOG_FILE, LOG_ROOT, flushAfter: 1); var eventLog = new EventLog(SEEMPLEST_LOG2); // --- Act WindowsEventLogger.RedirectLogTo(tracer); WindowsEventLogger.Log<WithStringNameAttribute>(); // --- Assert EventLog.Exists(SEEMPLEST_LOG2).ShouldBeFalse(); eventLog.Dispose(); var text = File.ReadAllText(Path.Combine(LOG_ROOT, LOG_FILE)); var lines = text.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); lines.ShouldHaveCountOf(1); var parts = lines[0].Split(new[] { "\t" }, StringSplitOptions.RemoveEmptyEntries); parts[1].ShouldEqual("Informational"); parts[4].ShouldEqual("Windows Event Trace"); parts[5].ShouldEqual("Default message"); parts[6].ShouldEqual("EventId: 3, CategoryId: 5"); }
public void LogWithRedirectionWorksWithExceptionMessage() { // --- Arrange if (!Directory.Exists(LOG_ROOT)) { Directory.CreateDirectory(LOG_ROOT); } File.Delete(Path.Combine(LOG_ROOT, LOG_FILE)); var tracer = new FileTraceLogger(LOG_FILE, LOG_ROOT, flushAfter: 1); var eventLog = new EventLog(SEEMPLEST_LOG2); // --- Act WindowsEventLogger.RedirectLogTo(tracer); WindowsEventLogger.Log<SampleError>(new NullReferenceException()); // --- Assert EventLog.Exists(SEEMPLEST_LOG2).ShouldBeFalse(); eventLog.Dispose(); var text = File.ReadAllText(Path.Combine(LOG_ROOT, LOG_FILE)); var lines = text.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); lines.ShouldHaveCountOf(3); var parts = lines[0].Split(new[] { "\t" }, StringSplitOptions.RemoveEmptyEntries); parts[1].ShouldEqual("Error"); }
private void SendMailMessage(MailMessage message, string smtpserver) { try { mailSender = new SmtpClient(); if (string.IsNullOrEmpty(mailSender.Host)) mailSender.Host = smtpserver; mailSender.Send(message); mailSender.SendCompleted += mailSender_SendCompleted; } catch (Exception ee) { EventLog Logger = new EventLog(); Logger.Source = "WebGrid.Util.Mail"; Logger.WriteEntry(ee.ToString(), EventLogEntryType.Error); Logger.Dispose(); } }
private static void mailSender_SendCompleted(object sender, AsyncCompletedEventArgs e) { if (e.Error == null) return; EventLog Logger = new EventLog(); Logger.Source = "WebGrid.Util.Mail"; Logger.WriteEntry(e.Error.ToString(), EventLogEntryType.Error); Logger.Dispose(); }
/// <summary> /// Translates Syslog messages to Eventlog messages /// Using Pri part as source, and log them to Windows EventLog /// </summary> /// <param name="endPoint">IP/port number from datagram sender</param> /// <param name="strReceived">Syslog message</param> private void Log(EndPoint endPoint, string strReceived) { Pri pri = new Pri(m_regex.Match(strReceived).Groups[1].Value); EventLogEntryType eventLogEntryType = Severity2EventLogEntryType(pri.Severity); string strMessage = string.Format("{0} : {1}", endPoint, m_regex.Replace(strReceived, evaluator)); EventLog myLog = new EventLog(m_EventLog); myLog.Source = pri.ToString(); myLog.WriteEntry(strMessage, eventLogEntryType); myLog.Close(); myLog.Dispose(); }
/// <summary> /// Logs the error. /// </summary> /// <param name="err">The err.</param> private static void LogTheError(string err) { const string eventLogName = "AKSite"; const string sourceName = "SiteErrors"; var eventLog = new EventLog {Log = eventLogName, Source = sourceName}; const string keyName = @"SYSTEM\CurrentControlSet\Services\EventLog\" + eventLogName + @"\" + sourceName; var rkEventSource = Registry.LocalMachine.OpenSubKey(keyName); if (rkEventSource == null) { var proc = new Process(); var procStartInfo = new ProcessStartInfo("Reg.exe") {Arguments = @"add HKLM\" + keyName, UseShellExecute = true, Verb = "runas"}; proc.StartInfo = procStartInfo; proc.Start(); } try { eventLog.WriteEntry(err,EventLogEntryType.Error); } catch { Debug.Print("failed to write key"); } finally { eventLog.Dispose(); } }
/// <summary> /// Initializes a custom event log for an instance of this class. /// </summary> private void InitializeCustomEventLog() { EventLog evtLog = new EventLog(LogName); evtLog.Source = SourceName; try { if (!EventLog.SourceExists(SourceName) || !EventLog.Exists(LogName)) EventLog.CreateEventSource(SourceName, LogName); } finally { evtLog.Dispose(); } }
void ErrorHandler(string strMessage) { try { if (!EventLog.SourceExists(strMessage)) { EventLog.CreateEventSource("Application", "Application", "."); } EventLog objLog = new EventLog(); objLog.Source = "WebSite Monitor"; strMessage = "Time " + System.DateTime.Now + " Error Message: " + strMessage; objLog.WriteEntry(strMessage, EventLogEntryType.Error); objLog.Close(); objLog.Dispose(); } catch//(Exception BTH) // "BAD THING HAPPENED" { // Not good if can't log to event log, but don't just blow up! // throw new ApplicationException("2> Unable to Write to Event Log",BTH); } }
void writeToEventLog(string strResult) { try { if (!EventLog.SourceExists("Application")) { EventLog.CreateEventSource("Application", "Application", "."); } EventLog objLog = new EventLog(); objLog.Source = "WebSite Monitor"; objLog.WriteEntry(strResult, EventLogEntryType.Error); objLog.Close(); objLog.Dispose(); } catch // (Exception ex) { // Not good if can't log to event log, but don't just blow up! // throw new ApplicationException("1> Unable to Write to Event Log",ex); } }
public static void WriteToEventLog(string sLogName, string sLogSource, string sErrorDetail,EventLogEntryType evType) { EventLog HourlyDailyEventLog = new EventLog(); try { if (!(EventLog.SourceExists(sLogName))) { CreateLog(sLogName); } HourlyDailyEventLog.Source = sLogName; HourlyDailyEventLog.WriteEntry(Convert.ToString(sLogSource) + Convert.ToString(sErrorDetail), evType); } catch (Exception ex) { HourlyDailyEventLog.Source = sLogName; HourlyDailyEventLog.WriteEntry(Convert.ToString("INFORMATION: ") + Convert.ToString(ex.Message), EventLogEntryType.Error); } finally { HourlyDailyEventLog.Dispose(); HourlyDailyEventLog = null; } }
/// <summary> /// Button "Refresh" on EventLog TabPage /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void btEventLogRefresh_Click(object sender, EventArgs e) { this.btEventLogRefresh.Enabled = false; await Task.Run(() => { dgEventLog.Rows.Clear(); if (EventLog.SourceExists(Constants.DKIM_SIGNER_EVENTLOG_SOURCE)) { EventLog oLogger = new EventLog(); try { oLogger.Log = EventLog.LogNameFromSourceName(Constants.DKIM_SIGNER_EVENTLOG_SOURCE, "."); } catch (Exception ex) { oLogger.Dispose(); MessageBox.Show(this, "Couldn't get EventLog source:\n" + ex.Message, "Error getting EventLog", MessageBoxButtons.OK, MessageBoxIcon.Error); this.btEventLogRefresh.Enabled = true; return; } for (int i = oLogger.Entries.Count - 1; i > 0; i--) { EventLogEntry oEntry; try { oEntry = oLogger.Entries[i]; } catch (Exception ex) { oLogger.Dispose(); MessageBox.Show(this, "Couldn't get EventLog entry:\n" + ex.Message, "Error getting EventLog", MessageBoxButtons.OK, MessageBoxIcon.Error); this.btEventLogRefresh.Enabled = true; return; } if (oEntry.Source != Constants.DKIM_SIGNER_EVENTLOG_SOURCE) { continue; } Image oImg = null; switch (oEntry.EntryType) { case EventLogEntryType.Information: oImg = SystemIcons.Information.ToBitmap(); break; case EventLogEntryType.Warning: oImg = SystemIcons.Warning.ToBitmap(); break; case EventLogEntryType.Error: oImg = SystemIcons.Error.ToBitmap(); break; case EventLogEntryType.FailureAudit: oImg = SystemIcons.Error.ToBitmap(); break; case EventLogEntryType.SuccessAudit: oImg = SystemIcons.Question.ToBitmap(); break; } this.dgEventLog.BeginInvoke(new Action(() => dgEventLog.Rows.Add(oImg, oEntry.TimeGenerated.ToString("yyyy-MM-ddTHH:mm:ss.fff"), oEntry.Message))); } oLogger.Dispose(); } }); this.btEventLogRefresh.Enabled = true; }
public void LogAfterResetWorksAsExpected() { // --- Arrange if (!Directory.Exists(LOG_ROOT)) { Directory.CreateDirectory(LOG_ROOT); } File.Delete(Path.Combine(LOG_ROOT, LOG_FILE)); var tracer = new FileTraceLogger(LOG_FILE, LOG_ROOT, flushAfter: 1); var eventLog = new EventLog(SEEMPLEST_LOG2); WindowsEventLogger.RedirectLogTo(tracer); WindowsEventLogger.Log<WithStringNameAttribute>(); // --- Act WindowsEventLogger.Reset(); WindowsEventLogger.Log<WithStringNameAttribute>(); // --- Assert var after = eventLog.Entries; var afterCount = after.Count; afterCount.ShouldEqual(1); var lastentry = after[after.Count - 1]; lastentry.Category.ShouldEqual("(5)"); lastentry.InstanceId.ShouldEqual(3); lastentry.Message.ShouldEqual("Default message"); lastentry.Source.ShouldEqual(SEEMPLEST_SOURCE); lastentry.EntryType.ShouldEqual(EventLogEntryType.Information); eventLog.Dispose(); }
protected void gravarExcecao(Usuario usuarioRemetente, long hashEntidadeRemetente, Exception objetoExcecao, short tipoExcecao, string siglaIdioma) { string tituloAplicacao = string.Empty; string mensagemRegistro = string.Empty; string origemErro = string.Empty; EventLog registroEventoSistema = new EventLog(); EventLogEntryType tipoEntradaRegistro = EventLogEntryType.Information; TradutorIdioma tradutorIdioma = new TradutorIdioma(siglaIdioma); mensagemRegistro = string.Format(tradutorIdioma.traduzirMensagem("MensagemExcecaoSistema"), objetoExcecao.Message, usuarioRemetente.Apelido, hashEntidadeRemetente, objetoExcecao.StackTrace); tituloAplicacao = tradutorIdioma.traduzirTexto("SGE_TituloAplicacao"); origemErro = string.Concat("SGE.v2 : ", objetoExcecao.Message.Substring(0, objetoExcecao.Message.Length >= 203 ? 203 : objetoExcecao.Message.Length)); if (!EventLog.SourceExists(origemErro)) EventLog.CreateEventSource(origemErro, tituloAplicacao); registroEventoSistema.Source = origemErro; registroEventoSistema.Log = tituloAplicacao; switch (tipoExcecao) { case TipoExcecao.Informacao: tipoEntradaRegistro = EventLogEntryType.Information; break; case TipoExcecao.Alerta: tipoEntradaRegistro = EventLogEntryType.Warning; break; case TipoExcecao.Erro: tipoEntradaRegistro = EventLogEntryType.Error; break; } registroEventoSistema.WriteEntry(mensagemRegistro, tipoEntradaRegistro); registroEventoSistema.Dispose(); tradutorIdioma = null; }
public void Create() { string builtInSourceName = string.Concat(_logName, "Instrumentation"); bool sourcesContainedBuildIn = false; // create sources foreach (string source in _sources) { CreateSource(source); if (source == builtInSourceName) sourcesContainedBuildIn = true; } if (!sourcesContainedBuildIn) { CreateSource(builtInSourceName); } using (EventLog eventLog = new EventLog(_logName, _machineName, builtInSourceName)) { eventLog.ModifyOverflowPolicy(OverflowAction.OverwriteAsNeeded, 14); eventLog.MaximumKilobytes = _logSizeInMegaBytes * 1024; eventLog.WriteEntry("Log created.", EventLogEntryType.Information); eventLog.Dispose(); } }
public void LogRedirectionConvertsTypesAsExpected() { // --- Arrange if (!Directory.Exists(LOG_ROOT)) { Directory.CreateDirectory(LOG_ROOT); } File.Delete(Path.Combine(LOG_ROOT, LOG_FILE)); var tracer = new FileTraceLogger(LOG_FILE, LOG_ROOT, flushAfter: 1); var eventLog = new EventLog(SEEMPLEST_LOG2); // --- Act WindowsEventLogger.RedirectLogTo(tracer); WindowsEventLogger.Log<SampleError>(); WindowsEventLogger.Log<SampleWarning>(); WindowsEventLogger.Log<SampleInformation>(); WindowsEventLogger.Log<SampleFailureAudit>(); WindowsEventLogger.Log<SampleSuccessAudit>(); // --- Assert EventLog.Exists(SEEMPLEST_LOG2).ShouldBeFalse(); eventLog.Dispose(); var text = File.ReadAllText(Path.Combine(LOG_ROOT, LOG_FILE)); var lines = text.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); lines.ShouldHaveCountOf(5); var expectedCats = new[] {"Error", "Warning", "Informational", "Error", "Success"}; for (var i = 0; i < 5; i++) { var parts = lines[i].Split(new[] { "\t" }, StringSplitOptions.RemoveEmptyEntries); parts[1].ShouldEqual(expectedCats[i]); } }
private void read_single_log_thread(log_info log) { string query_string = "*"; if (provider_name != "") query_string = "*[System/Provider/@Name=\"" + provider_name + "\"]"; int max_event_count = int.MaxValue; // debugging - load much less, faster testing if (util.is_debug) max_event_count = 250; try { // we can read the number of entres only for local logs if (provider_name == "" && log.remote_machine_name == "") { var dummy_log = new EventLog(log.log_type); lock(this) log.full_log_count_ = dummy_log.Entries.Count; dummy_log.Dispose(); } // waiting for user to set the password if ( log.remote_machine_name != "") while ( remote_password_ == "") Thread.Sleep(100); SecureString pwd = new SecureString(); foreach ( char c in remote_password_) pwd.AppendChar(c); EventLogSession session = log.remote_machine_name != "" ? new EventLogSession(log.remote_machine_name, remote_domain_name, remote_user_name, pwd, SessionAuthentication.Default) : null; pwd.Dispose(); EventLogQuery query = new EventLogQuery(log.log_type, PathType.LogName, query_string); query.ReverseDirection = reverse_; if ( session != null) query.Session = session; EventLogReader reader = new EventLogReader(query); int read_idx = 0; for (EventRecord rec = reader.ReadEvent(); rec != null && !log.disposed_ && read_idx++ < max_event_count ; rec = reader.ReadEvent()) lock (this) { log.last_events_.Add(rec); ++log.cur_log_count_; } lock (this) log.listening_for_new_events_ = true; // at this point, listen for new events if (reverse_) { // if reverse, I need to create another query, or it won't allow watching query = new EventLogQuery(log.log_type, PathType.LogName, query_string); if ( session != null) query.Session = session; } using (var watcher = new EventLogWatcher(query)) { watcher.EventRecordWritten += (o, e) => { lock(this) log.new_events_.Add(e.EventRecord); }; watcher.Enabled = true; while ( !log.disposed_) Thread.Sleep(100); } } catch (Exception e) { logger.Error("can't create event log " + log.log_type + "/" + remote_machine_name + " : " + e.Message); errors_.add("Can't create Log " + log.log_type + " on machine " + remote_machine_name + ", Reason=" + e.Message); } }
public void LogWithExceptionWorksAsExpected() { // --- Arrange var eventLog = new EventLog(SEEMPLEST_LOG2); // --- Act WindowsEventLogger.Log<WithStringNameAttribute>(new NullReferenceException()); // --- Assert var after = eventLog.Entries; var afterCount = after.Count; afterCount.ShouldEqual(1); var lastentry = after[after.Count - 1]; lastentry.Category.ShouldEqual("(5)"); lastentry.InstanceId.ShouldEqual(3); lastentry.Message.StartsWith("An unexcepted exception").ShouldBeTrue(); lastentry.Source.ShouldEqual(SEEMPLEST_SOURCE); lastentry.EntryType.ShouldEqual(EventLogEntryType.Information); eventLog.Dispose(); }
/// <summary> /// Worker thread, setting up an listening socket for UDP datagrams /// </summary> private void Worker() { Properties.Settings settings = new Properties.Settings(); m_EventLog = settings.EventLog; IPAddress ipAddress = IPAddress.Any; if(settings.Address!="*") ipAddress = IPAddress.Parse(settings.Address); IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, settings.Port); m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); m_socket.Bind(ipEndPoint); // Recycling vars , i love it. EndPoint endPoint = ipEndPoint; // http://www.ietf.org/rfc/rfc3164.txt // 4.1 syslog Message Parts // The total length of the packet MUST be 1024 bytes or less. byte[] buffer = new byte[1024]; while (m_running) { try { int intReceived = m_socket.ReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref endPoint); string strReceived = Encoding.ASCII.GetString(buffer, 0, intReceived); Log(endPoint, strReceived); } catch (Exception exception) { EventLog myLog = new EventLog(); myLog.Source = settings.ServiceName; if (!m_running) myLog.WriteEntry("Stopping...", EventLogEntryType.Information); else myLog.WriteEntry(exception.Message, EventLogEntryType.Error); myLog.Close(); myLog.Dispose(); } } }
public void LogWithLongMessageWorksAsExpected() { // --- Arrange var eventLog = new EventLog(SEEMPLEST_LOG2); // --- Act WindowsEventLogger.Log<WithStringNameAttribute>("Haho".PadRight(100000, '.')); // --- Assert var after = eventLog.Entries; var afterCount = after.Count; afterCount.ShouldEqual(1); var lastentry = after[after.Count - 1]; lastentry.Category.ShouldEqual("(5)"); lastentry.InstanceId.ShouldEqual(3); lastentry.Message.StartsWith("Haho...").ShouldBeTrue(); lastentry.Source.ShouldEqual(SEEMPLEST_SOURCE); lastentry.EntryType.ShouldEqual(EventLogEntryType.Information); eventLog.Dispose(); }
private void MainThread() { eventLog1.BeginInit(); DataRow dr = null; bool bLogged = false; TvMain = new STKTVMain.TVMain(); try { if (TvMain.Init() == true) { bLogged = true; } else { WarningReport("Unable to login, check credentials"); InfoReport(TvMain.GetEnvInfo()); return; } } catch (Exception Ex) { ErrorReport("Login failed, try again... " + Ex.Message); InfoReport(TvMain.GetEnvInfo()); } //InfoReport("DB Initialization OK"); System.Data.DataTable oRS; if (bLogged) { oRS = null; String q; q = "select plancall.*,npip,nppassword,ipport,transport,sysdate ServerDate from bdevices join plancall on bdevices.id_bd=plancall.id_bd where ( nplock is null or nplock <sysdate ) and npquery=1 " + " and bdevices.id_bd=" + DivID.ToString() + " "; oRS = TvMain.QuerySelect(q); if (oRS != null) { if (oRS.Rows.Count > 0) { try { dr = oRS.Rows[0]; DeviceThread(dr); } catch (Exception Ex) { ErrorReport("Прибор ID= " + DivID.ToString() + " error:" + Ex.Message); dr = null; } } oRS = null; } try { //InfoReport("Closing Device thread..."); //dr = null; TvMain.ClearDuration(); // close transport TvMain.DeviceClose(); TvMain.CloseDBConnection(); TvMain = null; eventLog1.Dispose(); return; } catch (Exception Ex) { ErrorReport("Closing DeviceThread error:" + Ex.Message); } } }
private void OpenUrl(string url, string data, UploadDataCompletedEventHandler eventhandler, object userToken, bool nop) { wc = new WebClient(); wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); if (eventhandler != null) wc.UploadDataCompleted += eventhandler; byte[] postByteArray = Encoding.ASCII.GetBytes(data); try { wc.UploadData(new Uri(url), "POST", postByteArray); wc.UploadDataCompleted += wc_UploadDataCompleted; } catch (Exception e) { EventLog logger = new EventLog(); logger.Source = "WebGrid"; logger.WriteEntry(e.ToString(), EventLogEntryType.Error); logger.Dispose(); } }