Search code examples
c#xunit

Where in my static class can I initialize a Trace Listener?


I want to add Debug and Trace to a class that I've created. However, I don't know where in my code to initialize a Trace Listener.

Here is the code I want to add to my static class:

Trace.Listeners.Add(
    new TextWriterTraceListener(
       File.CreateText("log.txt")
    )
);
Trace.AutoFlush = true;

Here is the class to which I want to add the Trace Listener:

using System;
using System.Diagnostics;
using System.IO;


namespace Example.Shared
{
    public static class ExampleClass
    {
        public static string SaySomething()
        {
            Trace.WriteLine($"I'm gonna say something");
            return "Something";
        }

        // etc.
    }
}

Apart from this class, I have only created some unit tests using Xunit. I have not yet created the application that will use this class.

This is what the unit test code looks like:

using Example.Shared;
using Xunit;

namespace ClassLibTests
{
    public class ExampleClassTests
    {
        [Fact]
        public void TestSaySomething()
        {
            string expected = "Something";
            string actual = ExampleClass.SaySomething();

            Assert.Equal(expected, actual);
        }
        // etc.
    }
}

I execute the above tests at the command line with the command dotnet test.


Solution

  • In order to initialize any static class or static members of a class you can use static constructors. So, you can update your code as follow:

    using System;
    using System.Diagnostics;
    using System.IO;
    
    namespace Example.Shared;
    
    public static class ExampleClass
    {
        static ExampleClass()
        { 
            Trace.Listeners.Add(
                new TextWriterTraceListener(File.CreateText("log.txt"))
            );
            Trace.AutoFlush = true;
        }
    
        public static string SaySomething()
        {
            Trace.WriteLine($"I'm gonna say something");
            return "Something";
        }
    
        // etc.
    }
    

    For more details check: C# static class constructor https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors

    BTW, I've also updated code to use the newly introduced file scoped namespace. Less indentation. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-10.0/file-scoped-namespaces