2009-07-15 4 views
54

내 C# 코드에서 이벤트 뷰어에 쓰려고하는데 멋진 "개체 참조가 개체의 인스턴스로 설정되지 않았습니다."라는 메시지가 나타납니다. 나는이 코드에 대한 도움을 주었고, 그 코드의 잘못된 점이나 그것을 수행하는 더 좋은 방법에 대해 고맙게 생각한다. 내가 전화를 시도하고 어디C# 이벤트 뷰어에 쓰기

private void WriteToEventLog(string message) 
{ 
    string cs = "QualityDocHandler"; 
    EventLog elog = new EventLog(); 
    if (!EventLog.SourceExists(cs)) 
    { 
     EventLog.CreateEventSource(cs, cs); 
    } 
    elog.Source = cs; 
    elog.EnableRaisingEvents = true; 
    elog.WriteEntry(message); 
} 

을 그리고 여기에 : 다음은 이벤트 로그에 기록 내가 가진 무엇

다음
private readonly Random _rng = new Random(); 
private const string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
private string RandomString(int size) 
{ 
    try 
    { 
     char[] buffer = new char[size]; 
     for (int i = 0; i < size; i++) 
     { 
      buffer[i] = _chars[_rng.Next(_chars.Length)]; 
     } 
     return new string(buffer); 
    } 
    catch (Exception e) 
    { 
     WriteToEventLog(e.ToString()); 
     return null; 
    } 
} 
+0

어떤 줄이 오류입니까? – NikolaiDante

+0

스택 추적을 제공하십시오. –

+1

"개체 참조가 개체의 인스턴스로 설정되지 않았습니다."- NULL을 참조한다는 것을 의미합니다.이 경우 코드 줄을 아는 것이 훨씬 도움이됩니다. 그건 당신이 참조하는 NULL입니다. –

답변

87

문제는 아마 존재하지 않는 로그에 이벤트 원본을 만들려고합니다. "응용 프로그램"로그를 지정해야합니다. 또한

if (!EventLog.SourceExists(cs)) 
    EventLog.CreateEventSource(cs, "Application");  

EventLog.WriteEntry(cs, message, EventLogEntryType.Error); 

:

로 변경합니다 응용 프로그램은 (윈도우 인증 또는 위임을 통해) 로그인 한 사용자로 실행중인 경우, 셰어의 내부 사용자는 이벤트를 만들 수있는 권한이 없습니다 출처. 이 경우 ThreadPool 스레드를 사용하여 이벤트를 생성하는 것이 트릭입니다.이 스레드는 생성 될 때 App Pool이 실행되는 사용자의 보안 컨텍스트를 갖습니다.

22

내가 이벤트 로깅을 구현하는 방법입니다.

interface ILogger 
{ 
    void Debug(string text); 

    void Warn(string text); 

    void Error(string text); 
    void Error(string text, Exception ex); 
} 

내 구현 클래스는 매우 간단합니다 : 난은 EventLog를 인스턴스화하지 않는

class EventLogger : ILogger 
{ 
    public void Debug(string text) 
    { 
     EventLog.WriteEntry("MyAppName", text, EventLogEntryType.Information); 
    } 

    public void Warn(string text) 
    { 
     EventLog.WriteEntry("MyAppName", text, EventLogEntryType.Warning); 
    } 

    public void Error(string text) 
    { 
     EventLog.WriteEntry("MyAppName", text, EventLogEntryType.Error); 
    } 

    public void Error(string text, Exception ex) 
    { 
     Error(text); 
     Error(ex.StackTrace); 
    } 
} 

참고 내가 다른 로깅 메커니즘을 교체 할 수 있도록 나는 일반적인하는 ILogger 인터페이스를 만들었습니다.

private static readonly ILogger log = new EventLogger(); 

을 그리고 실제 사용은 다음과 같이이다 : 난 그냥 다음 참조가 내 로거 클래스를 사용하려면 (이 정적 팩토리 메소드에 의해 반환 가질 수)

try 
{ 
    // business logic 
} 
catch (Exception ex) 
{ 
    log.Error("Exception in MyMethodName()", ex); 
} 
+11

좋은데, 그의 실제 질문과 아무런 관련이 없습니다. O –

+8

사실,하지만 스택 트레이스가 없습니다. – Nelson

+0

기본 생성자 인'if (! EventLog.SourceExists (source))'가 존재하는지 확인하기 위해 추가 한 경우, 그리고 코드에서 설정 한'const string source' (또는 소품이나 생성자 재정의) 클래스를 통해 다시 사용하십시오.그런 다음 EventLogger 클래스를 인스턴스화 할 때마다 OP 오류가 발생하지 않도록 실제 오류가 발생합니다. 이 코드를 허용 된 답변과 함께 사용했습니다. +1 – ppumkin

1
private void WriteEventLogToFile() 
    { 
     try 
     { 
      using (EventLog eventLog = new EventLog("Application")) 
      { 
      // source for your event 
       eventLog.Source = "IAStorDataMgrSvc"; 

      // Syntax details 
      // eventLog.WriteEntry("details",type of event,event id); 
      eventLog.WriteEntry("Hard disk Failure details", EventLogEntryType.Information, 11); 
      } 
     } 
     catch (Exception) 
     { 
      throw; 
     } 
    } 
관련 문제