Best Way to Dynamically Set an Appender File Path

Best way to dynamically set an appender file path

You are doing this the hard way! Define your log4net config as XML in your application's configuration file and use %property{} to advantage:

<appender name="YourAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="~/App_Data/%property{LogName}" />
....
</appender>

This is dynamic -- you just have to set the log4net property "LogName" before you initialize log4net. Thus, in your code any time before you configure log4net, set the desired value of this property:

string LogName = GetType().Assembly.GetName().Name + ".log";
log4net.GlobalContext.Properties["LogName"] = LogName;

Of course, you may use any property name. I've chosen "LogName" for a simple example, but you can have one per application if you want, as long as your code knows what the correct property name is and what the correct value should be.

Dynamically set file path in log4rs

I realize the rolling_file type make it so that it automatically increments numbers to the log names! This is the example of what I did.

appenders:
default:
kind: console
encoder:
kind: pattern
pattern: "{h({d(%H:%M:%S)})} - {m}{n}"
log_file:
kind: rolling_file
append: true
path: "logs/log.log"
encoder:
pattern: "{h({d(%m-%d-%Y %H:%M:%S)})} - {m}{n}"
policy:
kind: compound
trigger:
kind: size
limit: 10mb
roller:
kind: fixed_window
base: 1
count: 100
pattern: "logs/log{}.log"

root:
level: info
appenders:
- default
- log_file

This generates log{}.log (replace {} with incrementing numbers) files within the logs folder after the file reaches 10MB of size. Since I set append: true the log file will keep accumulating until it reaches the size limit.

Hopefully this helps others too!

Log4J change File path dynamically

I think you meant "my.log" not "{my.log"

System.setProperty("my.log", "C:/logfile.log");

I wouldn't imagine you can change this once the logging has started so you need to set this as early in your program as possible.

BTW: You can sub-class FileAppender to make it behave any way you like.



Related Topics



Leave a reply



Submit