Reputation: 1293
Is there a way to make the name of the fileAppender variable? I.e. when I call an action on my controller which takes an object, I would like to write this to a log file. The name of the file would look something like : yyyyMMdd_hhmssms_[controller]_[method].json
this is what I have in my config-file:
<appender name="JsonFileAppender" type="log4net.Appender.RollingFileAppender" >
<file value="c:\temp\" />
<datePattern value="yyyyMMdd_hh.mm.ss.ms_%thread{CommonApplicationData}'.json'" />
<staticLogFileName value="false" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="5MB" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%message%newline" />
</layout>
</appender>
This returns the following filename : 20160224_01.30.28.3028_P1rea24{Co30onApplicaPionDaPa}.json
Upvotes: 0
Views: 3176
Reputation: 25475
You can access the appenders of your log4net configuration at run-time like so
var repository = (Hierarchy)LogManager.GetRepository();
var appenders = repository.GetAppenders().Where(x => x is FileAppender);
You can get specific appender then by name
var appender = appenders.FirstOrDefault(x => x.Name.Equals("MyAppeader"));
Once you have an appender you can modify it how you like. You want to set the filepath
appender.File = @"c:\folder\yyyyMMdd_hhmssms_[controller]_[method].json";
You should not have the do anything else as log4net should automatically start using the new configuration.
Placing this all into a little helper method, you'd get this
public static void SetAppenderPath(string appender, string path)
{
var repository = (Hierarchy)LogManager.GetRepository();
var appenders = repository.GetAppenders().Where(x => x is FileAppender);
var appender = appenders.FirstOfDefault(x => x.Name.Equals(appender));
if (appender == null)
{
throw new ConfigurationErrorsException("Appender not found (" + appender + ")");
}
appender.File = path;
}
...
LogHelper.SetAppenderPath("MyAppender", @"yyyyMMdd_hhmssms_[controller]_[method].json");
Upvotes: 2
Reputation: 432
one way is to set an Environment Variable in your code like:
Environment.SetEnvironmentVariable("APPENDER_FILE", "Your File Path");
and then, configure this environment variable in log4net XML:
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="${APPENDER_FILE}"/>
Upvotes: 6