55using System . Diagnostics ;
66using System . Globalization ;
77using System . Security ;
8+ using ExcelDna . Logging ;
89
910namespace ExcelDna . IntelliSense
1011{
@@ -77,10 +78,22 @@ public static void Initialize()
7778 {
7879 if ( ! s_LoggingInitialized )
7980 {
81+ LoggingSettings settings = new LoggingSettings ( ) ;
82+
8083 bool loggingEnabled = false ;
8184 // DOCUMENT: By default the TraceSource is configured to source only Warning, Error and Fatal.
8285 // the configuration can override this.
83- IntelliSenseTraceSource = new TraceSource ( TraceSourceName , SourceLevels . Warning ) ;
86+ IntelliSenseTraceSource = new TraceSource ( TraceSourceName , settings . SourceLevel ) ;
87+
88+ Debug . Print ( "{0} TraceSource created. Listeners:" , TraceSourceName ) ;
89+ foreach ( TraceListener tl in IntelliSenseTraceSource . Listeners )
90+ {
91+ Debug . Print ( " {0} - {1}" , tl . Name , tl . TraceOutputOptions ) ;
92+ if ( tl . Name == "Default" && settings . DebuggerLevel . HasValue )
93+ {
94+ tl . Filter = new DiagnosticsFilter ( settings . DebuggerLevel . Value ) ;
95+ }
96+ }
8497
8598 try
8699 {
@@ -100,8 +113,19 @@ public static void Initialize()
100113 Close ( ) ;
101114 loggingEnabled = false ;
102115 }
116+
103117 if ( loggingEnabled )
104118 {
119+ if ( ! string . IsNullOrWhiteSpace ( settings . FileName ) )
120+ {
121+ Trace . AutoFlush = true ;
122+
123+ TextWriterTraceListener textWriterTraceListener = new TextWriterTraceListener ( settings . FileName , "FileWriter" ) ;
124+ if ( settings . FileLevel . HasValue )
125+ textWriterTraceListener . Filter = new DiagnosticsFilter ( settings . FileLevel . Value ) ;
126+ IntelliSenseTraceSource . Listeners . Add ( textWriterTraceListener ) ;
127+ }
128+
105129 AppDomain currentDomain = AppDomain . CurrentDomain ;
106130 //currentDomain.UnhandledException += UnhandledExceptionHandler;
107131 currentDomain . DomainUnload += AppDomainUnloadEvent ;
@@ -147,8 +171,14 @@ static void AppDomainUnloadEvent(object sender, EventArgs e)
147171
148172 static void Close ( )
149173 {
174+ AppDomain currentDomain = AppDomain . CurrentDomain ;
175+ currentDomain . DomainUnload -= AppDomainUnloadEvent ;
176+ currentDomain . ProcessExit -= ProcessExitEvent ;
177+
150178 if ( IntelliSenseTraceSource != null )
151179 IntelliSenseTraceSource . Close ( ) ;
180+
181+ s_LoggingInitialized = false ;
152182 }
153183
154184 }
@@ -249,4 +279,5 @@ public void Error(Exception ex, string message, params object[] args)
249279 static internal Logger Display { get ; } = new Logger ( IntelliSenseTraceEventId . Display ) ;
250280 static internal Logger Monitor { get ; } = new Logger ( IntelliSenseTraceEventId . Monitor ) ;
251281 }
282+
252283}
0 commit comments