jqno
jqno

Reputation: 15530

Log4net output to My Documents

In our C# app, we write files to Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments). Our log4net logfile should go there too, so we've defined application.conf as follows:

<appender name="LogFile" type="log4net.Appender.RollingFileAppender">
  <appendToFile value="true"/>
  <file value="%USERPROFILE%\My Documents\MyApp\log.txt"/>
  ...snip...
</appender>

This works, until we run in on a PC which has a non-English Windows. Because then, SpecialFolder.MyDocuments points to the folder Mijn Documenten, while the log still goes to My Documents. Confusion ensues, because now our files are in two places.

I want to write my log to the "real" My Documents folder. How do I do this?

I'm running out of ideas!

Upvotes: 10

Views: 4509

Answers (3)

mcfroob
mcfroob

Reputation: 1154

The accepted answer is out of date.

You should now use:

<file value="${UserProfile}\Documents\log-messages.log" />

(This should work even on Windows 7, where "Documents" is referred to by the alias "My Documents".)

${UserProfile} will map to C:\Users[UserName], even if you don't see this variable explicitly defined in your environment variable list.

Upvotes: 3

Alex
Alex

Reputation: 13244

There seem to be at least 2 approaches. The simplest is kind of a hack:

  1. Specify a custom environment variable to indicate the root path in you log4net config:

    <file value="%MYAPP_USER_ROOTFOLDER%\MyApp\log.txt"/>

  2. At startup, before initializing logging, set this environment variable value:

    Environment.SetEnvironmentVariable("MYAPP_USER_ROOTFOLDER", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));

The more complicated but recommended approach is explained here: http://marc.info/?l=log4net-user&m=110142086820117&w=2 and here http://ziqbalbh.com/articles/log4net-another-way-to-change-log-file-location-on-runtime/

Upvotes: 1

sgmoore
sgmoore

Reputation: 16077

Change the line

<file value="%USERPROFILE%\My Documents\MyApp\log.txt"/>

to

<file type="log4net.Util.PatternString" value="%envFolderPath{MyDocuments}\MyApp\log.txt" />

Upvotes: 10

Related Questions