Reputation: 1140
I'm setting upp Log4Net with configurations in web.config and want create text logs (RollingLogFileAppender)
based on a property in the data combined with todays date. (This was able in code earlier but was a bit ugly so moving everything to web.config):
Something like this BOOKINGS_20160405.txt
.
So if the data (a dictionary with key/values) which I want to log have a key called Source: BOOKING
, I want the result above. This Source can contain several other categories, and should be saved into those log file.
I tried several approaches with datePattern
but cannot find any solution.
Is this even possible without writing some code for it? Maybe I should not use RollingLogFileAppender at all for this?
Maybe I can create a custom appended making what I want?
Upvotes: 0
Views: 85
Reputation: 1140
So I was not able to solve it by pure <log4net>-configuration
. What I wanted to achieve was maximum configurable appenders, where I did not have to change code and recompile on changes.
But, I went with the code anyway to get it to work. Maybe it helps someone else. Looked something like this:
public class FileAppender : IAppender
{
public void RegisterLogger(ILoggerRepository repository, IConfig config)
{
if (!config.isActive) return;
if (repository.GetAppenders().Any(x => x.Name.Equals(config.logName, StringComparison.InvariantCultureIgnoreCase))) return;
if (config.path.EndsWith(@"\") == false)
path += @"\";
var rollingFileAppender = new RollingFileAppender
{
Name = config.logName,
AppendToFile = true,
File = config.path,
RollingStyle = RollingFileAppender.RollingMode.Date,
StaticLogFileName = false,
DatePattern = $"'{config.logName}_'yyyyMMdd'.log'",
LockingModel = new log4net.Appender.FileAppender.MinimalLock(),
Layout = new log4net.Layout.PatternLayout("%date %-5[%level] - %message%newline"),
};
var filters = new List<log4net.Filter.IFilter>() {
new log4net.Filter.LoggerMatchFilter() { LoggerToMatch = config.logName, AcceptOnMatch = true },
new log4net.Filter.DenyAllFilter(),
};
foreach (var filter in filters)
{
filter.ActivateOptions();
rollingFileAppender.AddFilter(filter);
}
rollingFileAppender.ActivateOptions();
log4net.Config.BasicConfigurator.Configure(rollingFileAppender);
}
public void Write(IConfig config, LogData data)
{
if (!config.isActive) return;
var textLogger = LogManager.GetLogger(config.logName);
var text = $"{data.Sender} - {data.Ip} - {data.Locator} - {data.Text} - {data.Args}";
textLogger.Info(text);
}
}
Upvotes: 1