how to customize tracelistener file location

Beantwortet how to customize tracelistener file location

  • Montag, 16. April 2012 03:09
     
      Enthält Code

    Hello.

    I'm using the app.config to create a log file for my application. Is there a way to customize it, so I set the path to a specific location?

    I want to place the log file in the user's application data folder. My app.config looks like this:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    	<startup/>
      <system.diagnostics>
        <trace autoflush="true" indentsize="4">
          <listeners>
            <add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="${USERPROFILE}\Application Data\MyApp\MyApp.log" />
            <remove name="Default" />
          </listeners>
        </trace>
      </system.diagnostics>
    </configuration>
    

    But it doesn't work. Can you give me an idea of how to do this? Is it even possible?

    Thanks.


Alle Antworten

  • Montag, 16. April 2012 05:59
     
     Beantwortet Enthält Code

    I am not sure whether we can use environment variables in App.config file.   So if your log file is under %userprofile%, then I suggest  you to create such a trace listener programmatically instead of using app.config file.

    string logFilePath = Environment.ExpandEnvironmentVariables("%userprofile%") + @"\AppData\MyApp\MyApp.log";
    FileStream hlogFile = new FileStream(logFilePath, FileMode.OpenOrCreate, FileAccess.Write);
    TextWriterTraceListener myListener = new TextWriterTraceListener(hlogFile);
    Trace.Listeners.Add(myListener);
    Trace.WriteLine("Sample Log");


    Please mark this post as answer if it solved your problem. Happy Programming!


    • Bearbeitet AdaveshMVP Montag, 16. April 2012 06:04
    • Als Antwort markiert jaybeev Montag, 16. April 2012 09:44
    •  
  • Montag, 16. April 2012 09:44
     
     
    Thank you so much. Exactly what I needed!