#if NETSTANDARD2_0
using System.Collections.Concurrent;
using System.IO;
using System.Reflection;
using System.Xml;
using log4net.Repository;
using Microsoft.Extensions.Logging;
namespace ServiceStack.Logging.Log4Net
{
public class Log4NetProvider : ILoggerProvider
{
///
/// The Dictionary containing the associated logger implementations of each category
///
private readonly ConcurrentDictionary loggers =
new ConcurrentDictionary();
public Log4NetProvider()
{
}
public Log4NetProvider(string log4NetConfigFile)
{
Parselog4NetConfigFile(log4NetConfigFile);
}
///
/// Create a new implementation for a category
///
/// the category name.
///
public ILogger CreateLogger(string categoryName)
{
return loggers.GetOrAdd(categoryName, CreateLoggerImplementation);
}
///
/// Create a new implementation.
///
/// the name.
///
private Log4NetLogger CreateLoggerImplementation(string name)
{
return new Log4NetLogger(name);
}
///
/// Create a new implementation with a configuration file.
///
/// the name.
/// the file uri.
///
private Log4NetLogger CreateLoggerImplementation(string name, string log4NetConfigFile)
{
Parselog4NetConfigFile(log4NetConfigFile);
return new Log4NetLogger(name);
}
///
/// Parse a configuration file given his uri
///
/// the file uri.
private static void Parselog4NetConfigFile(string log4NetConfigFile)
{
ILoggerRepository rootRepository = log4net.LogManager.GetRepository(Assembly.GetEntryAssembly());
if (File.Exists(log4NetConfigFile))
log4net.Config.XmlConfigurator.ConfigureAndWatch(rootRepository, new FileInfo(log4NetConfigFile));
else
log4net.Config.XmlConfigurator.Configure(rootRepository);
}
public void Dispose()
{
loggers.Clear();
}
}
public static class Log4netExtensions
{
public static ILoggerFactory AddLog4Net(this ILoggerFactory factory, string log4NetConfigFile)
{
factory.AddProvider(new Log4NetProvider(log4NetConfigFile));
return factory;
}
public static ILoggerFactory AddLog4Net(this ILoggerFactory factory)
{
factory.AddProvider(new Log4NetProvider());
return factory;
}
}
}
#endif