本文整理汇总了C#中System.Diagnostics.EventLog.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# EventLog.Dispose方法的具体用法?C# EventLog.Dispose怎么用?C# EventLog.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Diagnostics.EventLog
的用法示例。
在下文中一共展示了EventLog.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: LogError
/// <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
}
}
}
示例2: SqlExceptionHandling
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();
}
示例3: Init
/// <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;
}
}
示例4: WriteEvent
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();
}
}
示例5: WriteLog
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();
}
}
示例6: gravarExcecao
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;
}
示例7: Log
/// <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();
}
示例8: btEventLogRefresh_Click
/// <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;
}
示例9: WriteToEventLog
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;
}
}
示例10: ExceptionLoggingWorksAsExpected
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();
}
示例11: WithTypeAttributeWorksAsExpected
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();
}
示例12: ErrorHandler
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);
}
}
示例13: LogTheError
/// <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();
}
}
示例14: SendMailMessage
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();
}
}
示例15: mailSender_SendCompleted
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();
}