Share via


how to customize tracelistener file location

Question

Monday, April 16, 2012 3:09 AM | 1 vote

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.

All replies (3)

Monday, April 16, 2012 5:59 AM âś…Answered | 2 votes

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!


Monday, April 16, 2012 9:44 AM

Thank you so much. Exactly what I needed!


Friday, September 26, 2014 8:00 AM

old thread that I happen to see...

I'd like to point out to use the AppData pointer (like %APPDATA%) as part of the profile customization options. That way you will automatically take profile folder redirection into account en you'll be independent on OS version.

And if this is just a functionality log and not a reporting log, then I'd rather see it put in AppData\Local, so you don't  polute profiles and inadvertently impact (roaming) profile performance (or use a central log location)

Going to Quantum Depth, Comming back Cosmos Adept