In a wcf net 6.0 service that I've been working on for a few days, NLog is used. There are several Class Libraries and in each of them there is always the same code, a simple copy-paste was done by changing only the name of the class.
This is the class present several times with different names SomeClass1LoggerService, SomeClass2LoggerService, SomeClass3LoggerService, SomeClass4LoggerService..... only class name a log file name are changing.
public class SomeClassLoggerService
{
public static LogFactory Instance { get { return _instance.Value; } }
private static Lazy<LogFactory> _instance = new Lazy<LogFactory>(BuildLogFactory);
private static LogFactory BuildLogFactory()
{
string basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string configFilePath = Path.Combine(basePath, "SomeClass.nlog");
LogFactory logFactory = new LogFactory();
logFactory.Configuration = new XmlLoggingConfiguration(configFilePath, logFactory);
return logFactory;
}
}
this the code to get the log instance:
static NLog.ILogger _Logger = SomeClassxLoggerService.Instance.GetCurrentClassLogger();
i tried to create a derived class like this:
public class SomeDerivedClassLoggerService:SomeClassLoggerService
{
}
but the problem is Assembly.GetExecutingAssembly() returns always the name and path of the base class, i need to create the log with derived class name and path. it seems to me there is no way to pass to SomeClassLoggerService the instance of derived class so i can create the log in the right place e with derived class name. in this sample the log file for SomeDerivedClassLoggerService should be named SomeDerivedClass.nlog e saved in the same path of SomeDerivedClass.dll
CodePudding user response:
Maybe you can use generics and pass the derived types as generic argument to the base class ? If this is acceptable you can write something like :
public abstract class SomeClassLoggerService<T> where T : SomeClassLoggerService<T>
{
public static LogFactory Instance { get { return _instance.Value; } }
private static Lazy<LogFactory> _instance = new Lazy<LogFactory>(BuildLogFactory);
private static LogFactory BuildLogFactory()
{
string basePath = Path.GetDirectoryName(typeof(T).Assembly.Location);
string configFilePath = Path.Combine(basePath, $"{typeof(T).Name}.nlog");
LogFactory logFactory = new LogFactory();
logFactory.Configuration = new XmlLoggingConfiguration(configFilePath, logFactory);
return logFactory;
}
}
public class SomeDerivedClassLoggerService : SomeClassLoggerService<SomeDerivedClassLoggerService>
{
}