.netspecial-folderstracelistener

How can .NET TraceListener be configured to log to TEMP folder


How can .NET TraceListener be configured to log to TEMP folder? Is it possible to do this in app.config like:

      <add type="System.Diagnostics.TextWriterTraceListener" 
          initializeData="%Temp%\logfilename.log"/>

.. without making any code changes?

Or can this only be done if you create your listener in code?


Solution

  • You'd have to set it in your code.

    As you can see in the source code, the constructor immediately assigns to file name with no parsing of the internal structure of the file name.

     public TextWriterTraceListener(string fileName, string name) : base(name) {
                this.fileName = fileName; 
            } 
    

    And then there is some code to deal with the possibility that the file is already locked, but nothing to deal with the possibility that the folder isn't writable (TEMP is usually a writable folder of last resort)

        string fullPath = Path.GetFullPath(fileName);
                        string dirPath = Path.GetDirectoryName(fullPath); 
                        string fileNameOnly = Path.GetFileName(fullPath);
    //more code
           fileNameOnly = Guid.NewGuid().ToString() + fileNameOnly;
                            fullPath = Path.Combine(dirPath, fileNameOnly);