chr
2026-04-05 fe750b791d5b517cc4e9bc8e99a9a75139a0cfba
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
//            Copyright Keysight Technologies 2012-2019
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, you can obtain one at http://mozilla.org/MPL/2.0/.
using System;
using System.Diagnostics;
using System.Reflection;
using System.IO;
using OpenTap.Diagnostic;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
 
namespace OpenTap
{
    /// <summary>
    /// Identifies the type of event that is logged.
    /// </summary>
    public enum LogEventType
    {
        /// <summary>
        ///     Recoverable error.
        /// </summary>
        Error = 10,
        /// <summary>
        ///     Noncritical problem.
        /// </summary>
        Warning = 20,
        /// <summary>
        ///     Informational message.
        /// </summary>
        Information = 30,
        /// <summary>
        ///     Debugging trace.
        /// </summary>
        Debug = 40
    }
 
    /// <summary>
    /// Encapsulates the features of the OpenTAP logging infrastructure.
    /// </summary>
    public class TraceSource
    {
        internal ILog log;
 
        /// <summary> The object that owns this trace source. </summary>
        internal object Owner;
        internal TraceSource(ILog logSource)
        {
            log = logSource;
        }
 
        LogContext.LogInjector redirectedLog => Log.RedirectedLog;
 
        /// <summary>
        /// Blocks until all messages posted up to this point have reached all TraceListeners.  
        /// </summary>
        public void Flush()
        {
            Log.Flush();
        }
 
        /// <summary>
        /// Register a single event.
        /// </summary>
        public void TraceEvent(LogEventType te, int id, string message)
        {
            
            if (message == null)
                throw new ArgumentNullException(nameof(message));
            if(redirectedLog != null)
                redirectedLog.LogEvent(log.Source, (int)te, message);
            else
                log.LogEvent((int)te, message);
        }
 
        /// <summary> Register a single event with formatting and duration. </summary>
        public void TraceEvent(long durationNs, LogEventType te, int id, string message, params object[] args)
        {
            if(redirectedLog != null)
                redirectedLog.LogEvent(log.Source, (int)te, durationNs, message, args);
            else
                log.LogEvent((int)te, durationNs, message, args);
        }
        
        /// <summary> Register a single event without formatting and duration. </summary>
        public void TraceEvent(long durationNs, LogEventType te, int id, string message)
        {
            // this overload is important since otherwise the logging system will use 
            // the overload with [args] even though there are none. And that can give
            // problems if the message itself contains formatting demarcations e.g '{0}'
            if (redirectedLog != null)
                redirectedLog.LogEvent(log.Source, (int)te, durationNs, message);
            else
                log.LogEvent((int)te, durationNs, message);
        }
 
        /// <summary>
        /// Register a single event with formatting
        /// </summary>
        public void TraceEvent(LogEventType te, int id, string message, params object[] args)
        {
            if (message == null)
                throw new ArgumentNullException(nameof(message));
            if (args == null)
                throw new ArgumentNullException(nameof(args));
            if(redirectedLog != null)
                redirectedLog.LogEvent(log.Source, (int)te, message, args);
            else
                log.LogEvent((int)te, message, args);
        }
    }
 
    /// <summary>
    /// Base class for various listeners.
    /// </summary>
    public class TraceListener : ILogListener
    {
        void ILogListener.EventsLogged(IEnumerable<Event> events)
        {
            TraceEvents(events);
        }
 
        /// <summary>
        /// Receives all log messages. The virtual method simply calls <see cref="TraceEvent(string, LogEventType, int, string)"/> directly.  
        /// </summary>
        public virtual void TraceEvents(IEnumerable<Event> events)
        {
            foreach (var evt in events)
                TraceEvent(evt.Source, (LogEventType)evt.EventType, 0, evt.Message);
        }
 
        /// <summary>
        /// Empty TraceEvent method.
        /// </summary>
        public virtual void TraceEvent(string source, LogEventType eventType, int id, string format)
        {
        }
 
        /// <summary>
        /// Empty TraceEvent method.
        /// </summary>
        public virtual void TraceEvent(string source, LogEventType eventType, int id, string format, params object[] args)
        {
            TraceEvent(source, eventType, id, string.Format(format, args));
        }
 
        /// <summary>
        /// Virtual method to match System.Diagnostics.TraceListener. Might be removed.
        /// </summary>
        public virtual void Write(string str)
        {
        }
 
        /// <summary>
        /// Virtual method to match System.Diagnostics.TraceListener. Might be removed.
        /// </summary>
        public virtual void WriteLine(string str)
        {
        }
 
        /// <summary>
        /// Waits until all sent log messages have been processed by this and all other TraceListeners.
        /// </summary>
        public virtual void Flush()
        {
            Log.Flush();
        }
    }
 
    /// <summary>
    /// Simple TraceListener which outputs data to a TextWriter.
    /// </summary>
    class TextWriterTraceListener : TraceListener, IDisposable
    {
        private TextWriter writer;
 
        readonly object lockObject = new object();
 
        /// <summary>
        /// The writer that is used as the output.
        /// </summary>
        public TextWriter Writer
        {
            get => writer;
            set
            {
                if (writer != value)
                {
                    lock(lockObject)
                        writer = value;
                }
            }
        }
 
        /// <summary>
        /// Creates a new TextWriterTraceListener writing to the given filename.
        /// </summary>
        public TextWriterTraceListener(string filename)
            : this(new FileStream(filename, FileMode.Append))
        {
        }
 
        /// <summary>
        /// Creates a new TextWriterTraceListener writing to the given stream.
        /// </summary>
        public TextWriterTraceListener(Stream stream)
        {
            Writer = new StreamWriter(stream);
        }
 
        /// <summary>
        /// Writes a string to the current Writer.
        /// </summary>
        public override void Write(string message)
        {
            lock(lockObject)
                Writer.Write(message);
        }
 
        /// <summary>
        /// Writes a string including a newline to the current Writer.
        /// </summary>
        public override void WriteLine(string message)
        {
            lock(lockObject)
                Writer.WriteLine(message);
        }
 
        /// <summary>
        /// Flushes the log system and the current Writer.
        /// </summary>
        public override void Flush()
        {
            base.Flush();
            lock(lockObject) 
                writer.Flush();
        }
 
        /// <summary>
        /// Frees up the writer.
        /// </summary>
        public void Dispose()
        {
            lock(lockObject)
            {
                if (writer != null)
                {
                    writer.Close();
                    writer = null;
                }
            }
        }
    }
 
    /// <summary>
    /// This class extends System.Diagnostics.Log to provide shorthand methods 
    /// for logging/tracing messages at different levels.
    /// </summary>
    public static class Log
    {
        static readonly LogContext rootLogContext = (LogContext)LogFactory.CreateContext();
 
        internal static ILogTimestampProvider Timestamper
        {
            get => rootLogContext.Timestamper;
            set => rootLogContext.Timestamper = value;
        }
 
        static readonly SessionLocal<LogContext.LogInjector> logField = new SessionLocal<LogContext.LogInjector>(null);
        static readonly SessionLocal<LogContext> sessionLogContext = new SessionLocal<LogContext>(rootLogContext);
 
        internal static void WithNewContext()
        {
            var ctx = new LogContext();
            
            logField.Value = new LogContext.LogInjector(ctx);
            sessionLogContext.Value = ctx;
        }
 
        internal static LogContext.LogInjector RedirectedLog => logField.Value;
 
        /// <summary> The current log context. </summary>
        public static ILogContext Context => sessionLogContext.Value;
 
        /// <summary> Makes a TraceListener start receiving log messages. </summary>
        /// <param name="listener">The TraceListener to add.</param>
        public static void AddListener(ILogListener listener)
        {
            if (listener == null)
                throw new ArgumentNullException(nameof(listener));
            var ctx = Context;
            ctx.Flush();
            ctx.AttachListener(listener);
        }
        
        /// <summary> Stops a specified TraceListener from receiving log messages. </summary>
        /// <param name="listener">The TraceListener to remove.</param>
        public static void RemoveListener(ILogListener listener)
        {
            if (listener == null)
                throw new ArgumentNullException(nameof(listener));
            var ctx = Context;
            listener.Flush();
            ctx.DetachListener(listener);
            listener.Flush();
        }
        /// <summary>
        /// Gets all added TraceListeners.
        /// </summary>
        /// <returns>A readonly collection of TraceListeners.</returns>
        public static ReadOnlyCollection<ILogListener> GetListeners()
        {
            return sessionLogContext.Value?.GetListeners();
        }
        /// <summary> Creates a new log source. </summary>
        /// <param name="name">The name of the Log.</param>
        /// <returns>The created Log.</returns>
        public static TraceSource CreateSource(string name)
        {
            return new TraceSource(rootLogContext.CreateLog(name));
        }
 
        // ConditionalWeakTable keys does not count as a reference and are automatically removed on GC. This way we avoid leak. CWT's are thread safe.
        static readonly System.Runtime.CompilerServices.ConditionalWeakTable<object, TraceSource> ownedTraceSources = new System.Runtime.CompilerServices.ConditionalWeakTable<object, TraceSource>();
        static readonly object addlock = new object();
        /// <summary> Creates a new owned log source. Note that any given object can only have one owned TraceSource.</summary>
        /// <param name="name">The name of the Log.</param>
        /// <param name="owner">The object owning the log. This is used to enable OpenTAP to emit log messages on behalf of the owner object. </param>
        /// <returns>The created Log.</returns>
        public static TraceSource CreateSource(string name, object owner)
        {
            if (owner == null)
                throw new ArgumentNullException(nameof(owner));
            var source = CreateSource(name);
            source.Owner = owner;
            lock (addlock)
            {
                ownedTraceSources.Remove(owner);
                ownedTraceSources.Add(owner, source); // in this version of .NET there is no Update method...
            }
            return source;
        }
        
        /// <summary> Gets the source of a specified owner. </summary>
        /// <param name="owner"></param>
        /// <returns>returns the TraceSource or null if the owner owns no source.</returns>
        public static TraceSource GetOwnedSource(object owner)
        {
            if (owner == null)
                throw new ArgumentNullException(nameof(owner));
            lock (addlock)
            {
                ownedTraceSources.TryGetValue(owner, out TraceSource source);
                return source;
            }
        }
 
        /// <summary>
        /// Removes a previously Created Log from the list of sources.
        /// </summary>
        /// <param name="source"></param>
        public static void RemoveSource(TraceSource source)
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));
            rootLogContext.RemoveLog(source.log);
        }
 
        static Log()
        {
            // This improves performance by disabling a critical region that the .NET framework 
            // would otherwise put around writing to _all_ listeners. With UseGlobalLock set to 
            // false instead, a critical region will only be put around each listener individually 
            // and only if they have IsThreadSafe=false. UseGlobalLock=false is also required to
            // prevent a deadlock when using the Log Breaking feature in the GUI.
            Trace.UseGlobalLock = false;
 
            rootLogContext.Async = true;
            rootLogContext.MessageBufferSize = 8 * 1024 * 1024;
        }
 
        // Performance: Reuse the string build each time to avoid generating GC pressure.
        [ThreadStatic]
        static StringBuilder sb;
 
        /// <summary>
        /// like traceEvent except it uses a stopwatch 'timer' to write formatted time after the message [{1:0}ms].
        /// Usually used to signal in the log how long an operation took.
        /// </summary>
        /// <param name="trace"></param>
        /// <param name="elapsed"></param>
        /// <param name="eventType"></param>
        /// <param name="message"></param>
        /// <param name="args"></param>
        static void traceEvent(this TraceSource trace, TimeSpan elapsed, LogEventType eventType, string message, params object[] args)
        {
            if (message == null)
                throw new ArgumentNullException(nameof(message));
            var timespan = ShortTimeSpan.FromSeconds(elapsed.TotalSeconds);
 
            if (sb == null)
                sb = StringBuilderCache.GetStringBuilder();
            sb.Clear();
            if (args.Length == 0)
            {
                sb.Append(message);
            }
            else
            {
                sb.AppendFormat(message, args);
            }
            sb.Append(" [");
            timespan.ToString(sb);
            sb.Append("]");
            // * 1_000_000 steals about 20 bits of precision
            // so ticks can be about 2^43 before overflowing (signed int)
            // 
            long durationNs = elapsed.Ticks * NanoSecondsPerTick;
            trace.TraceEvent(durationNs, eventType, 0, sb.ToString());
        }
 
        // this should always be exactly 100.
        const long NanoSecondsPerTick = 1_000_000_000 / TimeSpan.TicksPerSecond;
 
        /// <summary>
        /// Write a message to the log with a given trace level.
        /// </summary>
        /// <param name="trace"></param>
        /// <param name="eventType"></param>
        /// <param name="message"></param>
        /// <param name="args"></param>
        static void traceEvent(this TraceSource trace, LogEventType eventType, string message, params object[] args)
        {
            if (message == null)
                throw new ArgumentNullException(nameof(message));
            if (args.Length == 0)
            {
                trace.TraceEvent(eventType, 0, message);    
            }
            else
            {
                trace.TraceEvent(eventType, 0, message, args);
            }
            
        }
 
        static void exceptionEvent(this TraceSource trace, Exception exception, LogEventType eventType)
        {
            if (exception == null)
                throw new ArgumentNullException(nameof(exception));
            WriteException(trace, exception, eventType);
        }
 
        /// <summary>
        /// Trace a message at level "Information" (<see cref="LogEventType.Information"/>).
        /// </summary>
        /// <param name="trace">this(extension method).</param>
        /// <param name="message">Message to write.</param>
        public static void TraceInformation(this TraceSource trace, string message)
        {
            Info(trace, message);
        }
 
        /// <summary>
        /// Trace a message at level "Debug" (<see cref="LogEventType.Debug"/>).
        /// </summary>
        /// <param name="trace">this(extension method).</param>
        /// <param name="message">Message to write.</param>
        /// <param name="args">parameters (see <see cref="String.Format(string, object)"/>).</param>
        public static void Debug(this TraceSource trace, string message, params object[] args)
        {
            traceEvent(trace, LogEventType.Debug, message, args);
        }
 
        /// <summary>
        /// Writes a message with the time measured by timer appended in the format [xx.x (m/u/n)s].
        /// if timer is a TimerToken it will be disposed.
        /// Information level log message.
        /// </summary>
        /// <param name="trace"></param>
        /// <param name="timer"></param>
        /// <param name="message"></param>
        /// <param name="args"></param>
        public static void Info(this TraceSource trace, Stopwatch timer, string message, params object[] args)
        {
            if (timer == null)
                throw new ArgumentNullException("timer");
            traceEvent(trace, timer.Elapsed, LogEventType.Information, message, args);
        }
 
        /// <summary>
        /// Writes a message with the time measured by timer appended in the format [xx.x (m/u/n)s].
        /// if timer is a TimerToken it will be disposed.
        /// Debug level end message.
        /// </summary>
        /// <param name="trace"></param>
        /// <param name="timer"></param>
        /// <param name="message"></param>
        /// <param name="args"></param>
        public static void Debug(this TraceSource trace, Stopwatch timer, string message, params object[] args)
        {
            if (timer == null)
                throw new ArgumentNullException("timer");
            traceEvent(trace, timer.Elapsed, LogEventType.Debug, message, args);
        }
        /// <summary>
        /// Writes a message with the time measured by timer appended in the format [xx.x (m/u/n)s].
        /// if timer is a TimerToken it will be disposed.
        /// Warning level end message.
        /// </summary>
        /// <param name="trace"></param>
        /// <param name="timer"></param>
        /// <param name="message"></param>
        /// <param name="args"></param>
        public static void Warning(this TraceSource trace, Stopwatch timer, string message, params object[] args)
        {
            if (timer == null)
                throw new ArgumentNullException("timer");
            traceEvent(trace, timer.Elapsed, LogEventType.Warning, message, args);
        }
        /// <summary>
        /// Writes a message with the time measured by timer appended in the format [xx.x (m/u/n)s].
        /// if timer is a TimerToken it will be disposed.
        /// Error level end message.
        /// </summary>
        /// <param name="trace"></param>
        /// <param name="timer"></param>
        /// <param name="message"></param>
        /// <param name="args"></param>
        public static void Error(this TraceSource trace, Stopwatch timer, string message, params object[] args)
        {
            if (timer == null)
                throw new ArgumentNullException("timer");
            traceEvent(trace, timer.Elapsed, LogEventType.Error, message, args);
        }
 
        /// <summary>
        /// Writes a message with the time appended in the format [xx.x (m/u/n)s].
        /// if timer is a TimerToken it will be disposed.
        /// Information level log message.
        /// </summary>
        /// <param name="trace"></param>
        /// <param name="elapsed"></param>
        /// <param name="message"></param>
        /// <param name="args"></param>
        public static void Info(this TraceSource trace, TimeSpan elapsed, string message, params object[] args)
        {
            traceEvent(trace, elapsed, LogEventType.Information, message, args);
        }
 
        /// <summary>
        /// Writes a message with the time appended in the format [xx.x (m/u/n)s].
        /// if timer is a TimerToken it will be disposed.
        /// Debug level end message.
        /// </summary>
        /// <param name="trace"></param>
        /// <param name="elapsed"></param>
        /// <param name="message"></param>
        /// <param name="args"></param>
        public static void Debug(this TraceSource trace, TimeSpan elapsed, string message, params object[] args)
        {
            traceEvent(trace, elapsed, LogEventType.Debug, message, args);
        }
        
        /// <summary>
        /// Writes a message with the time appended in the format [xx.x (m/u/n)s].
        /// if timer is a TimerToken it will be disposed.
        /// Warning level end message.
        /// </summary>
        /// <param name="trace"></param>
        /// <param name="elapsed"></param>
        /// <param name="message"></param>
        /// <param name="args"></param>
        public static void Warning(this TraceSource trace, TimeSpan elapsed, string message, params object[] args)
        {
            traceEvent(trace, elapsed, LogEventType.Warning, message, args);
        }
        /// <summary>
        /// Writes a message with the time appended in the format [xx.x (m/u/n)s].
        /// if timer is a TimerToken it will be disposed.
        /// Error level end message.
        /// </summary>
        /// <param name="trace"></param>
        /// <param name="elapsed"></param>
        /// <param name="message"></param>
        /// <param name="args"></param>
        public static void Error(this TraceSource trace, TimeSpan elapsed, string message, params object[] args)
        {
            traceEvent(trace, elapsed, LogEventType.Error, message, args);
        }
        /// <summary>
        /// Trace a message at level "Information" (<see cref="LogEventType.Information"/>).
        /// </summary>
        /// <param name="trace">this(extension method).</param>
        /// <param name="message">Message to write.</param>
        /// <param name="args">parameters (see <see cref="String.Format(string, object)"/>).</param>
        public static void Info(this TraceSource trace, string message, params object[] args)
        {
            traceEvent(trace, LogEventType.Information, message, args);
        }
 
        /// <summary>
        /// Trace a message at level "Warning" (<see cref="LogEventType.Warning"/>).
        /// </summary>
        /// <param name="trace">this(extension method).</param>
        /// <param name="message">Message to write.</param>
        /// <param name="args">parameters (see <see cref="String.Format(string, object)"/>).</param>
        public static void Warning(this TraceSource trace, string message, params object[] args)
        {
            traceEvent(trace, LogEventType.Warning, message, args);
        }
 
        /// <summary>
        /// Trace a message at level "Error" (<see cref="LogEventType.Error"/>).
        /// </summary>
        /// <param name="trace">this(extension method).</param>
        /// <param name="message">Message to write.</param>
        /// <param name="args">parameters (see <see cref="String.Format(string, object)"/>).</param>
        public static void Error(this TraceSource trace, string message, params object[] args)
        {
            traceEvent(trace, LogEventType.Error, message, args);
        }
 
        /// <summary>
        /// Write exception details (including stack trace) to the trace at level "Debug" (<see cref="LogEventType.Error"/>). 
        /// </summary>
        /// <param name="trace">this(extension method).</param>
        /// <param name="exception">Inputs error exception.</param>
        public static void Debug(this TraceSource trace, Exception exception)
        {
            exceptionEvent(trace, exception, LogEventType.Debug);
        }
 
        /// <summary>
        /// Write exception details (including stack trace) to the trace at level "Error" (<see cref="LogEventType.Error"/>). 
        /// </summary>
        /// <param name="trace">this(extension method).</param>
        /// <param name="exception">Inputs error exception.</param>
        public static void Error(this TraceSource trace, Exception exception)
        {
            exceptionEvent(trace, exception, LogEventType.Error);
        }
 
        const int callerStackTraceLimit = 4;
        static void WriteStackTrace(TraceSource trace, StackTrace stack, LogEventType level)
        {
            var frames = stack.GetFrames() ?? Array.Empty<StackFrame>(); 
            var lines = frames
                .Skip(3) // Skip the frames from the logging itself.
                .Where(line => line.HasMethod()); // only take those with the method available.
            int lineCount = lines.Count();
            
            lines = lines.Take(callerStackTraceLimit); // Just show the top of the call stack.
            
            foreach (StackFrame line in lines)
            {
                var fixedLine =  $"at {line.GetMethod()}";
                if (line.HasSource())
                {
                    fixedLine += $" in {line.GetFileName()}:line {line.GetFileLineNumber()}";
                }
                trace.TraceEvent(level, 2, "    " + fixedLine, false);
            }
 
            if (lineCount > callerStackTraceLimit)
            {
                trace.TraceEvent(level, 2, "    ...");
            }
        }
 
        static void WriteException(TraceSource trace, Exception exception, LogEventType level, bool appendStack = true, bool isInner = false)
        {
            var exceptionName = exception.GetType().Name;
            try
            {
                var exceptionMessage = exception.Message
                    .Replace("{", "{{")
                    .Replace("}", "}}");
                if (isInner)
                    trace.TraceEvent(level, 2, "  Inner " + exceptionName + ": " + exceptionMessage, false);
                else
                    trace.TraceEvent(level, 2, exceptionName + ": " + exceptionMessage);
                if (exception.StackTrace != null)
                {
                    string[] lines = exception.StackTrace.Split(new char[] {'\n'});
                    foreach (string line in lines)
                    {
                        var fixedLine = line.Replace("{", "{{").Replace("}", "}}").Trim();
                        trace.TraceEvent(LogEventType.Debug, 2, "    " + fixedLine, false);
                    }
                }
 
                if (exception is ReflectionTypeLoadException)
                {
                    ReflectionTypeLoadException reflectionTypeLoadException = (ReflectionTypeLoadException) exception;
                    foreach (Exception ex in reflectionTypeLoadException.LoaderExceptions)
                    {
                        WriteException(trace, ex, level, false);
                    }
                }
                else if (exception is AggregateException ag)
                {
                    foreach (var inner in ag.InnerExceptions)
                    {
                        WriteException(trace, inner, level, false, true);
                    }
                }
                else if (exception.InnerException is Exception inner)
                {
                    WriteException(trace, inner, level, false, true);
                }
            }
            catch (Exception)
            {
                trace.TraceEvent(level, 2, "Error caught while logging an exception.");
            }
 
            if (appendStack)
            {
                try
                {
                    var stackTrace = new StackTrace(true);
                    trace.TraceEvent(level, 2, "Exception caught at:");
                    WriteStackTrace(trace, stackTrace, level);
                }
                catch
                {
                    trace.TraceEvent(level, 2, "Error retrieving current stacktrace.");
                }
            }
        }
 
        /// <summary>
        /// Flushes all waiting log trace events.
        /// </summary>
        public static void Flush()
        {
            rootLogContext.Flush();
        }
 
        /// <summary>
        /// Puts the current log context into synchronous mode.
        /// All TraceSources will now wait for their trace events to be handled by all TraceListeners before returning.
        /// </summary>
        public static void StartSync()
        {
            Flush();
            rootLogContext.Async = false;
        }
 
        /// <summary>
        /// Ends synchronous mode. Must be called after <c ref="StartSync"/>.
        /// </summary>
        public static void StopSync()
        {
            rootLogContext.Async = true;
            Flush();
        }
    }
 
    /// <summary>
    /// Extension methods for Exception.
    /// </summary>
    static class ExceptionExtensions
    {
        /// <summary>
        /// Finds the message of the inner most exception for this exception. If no inner exceptions are set, the message of this exception is returned.
        /// COMExceptions are ignored as their message is not very useful.
        /// </summary>
        public static string GetInnerMostExceptionMessage(this Exception ex)
        {
            if (ex is AggregateException ag)
            {
                if(ag.InnerExceptions.Count == 1)
                    return ag.InnerExceptions[0].GetInnerMostExceptionMessage();
                return ag.Message;
            }
            if (ex is System.Runtime.InteropServices.COMException)
                return ex.Message;
            return ex.InnerException?.GetInnerMostExceptionMessage() ?? ex.Message;
        }
 
        public static void Rethrow(this Exception ex)
        {
            System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex).Throw();
        }
 
        public static void RethrowInner(this Exception ex)
        {
            if(ex is AggregateException a && a.InnerExceptions.Count > 1)
                ex.Rethrow();
            else
                (ex.InnerException ?? ex).Rethrow();
        }
    }
 
    static class StringBuilderCache
    {
        [ThreadStatic]
        static StringBuilder sb;
 
        public static StringBuilder GetStringBuilder()
        {
            var sb2 = sb ??= new StringBuilder();
            sb2.Clear();
            return sb2;   
        }
    }
}