I would like to use the Topshelf instance name as part of the log4net log file name

When creating an instance of the service using TopShelf, I would like to access the name of the instance of the service (which may have been installed on the command line during installation as a service, which means that I do not have direct access to it) in order to be able to use this is as a property for the log file name in Log4Net.

In the following code example, we set various properties available for logging in a global context. I would also like to set the instance name of the service here; but doesn't seem to be able to access it during host initialization.

Any suggestions on how I can access the value of a service instance name at runtime using Topshelf.

The following example is part of a common function that all our services use to start a service using Topshelf.

public static TopshelfExitCode Run(Func<IConsumerController> controllerFactory, string serviceName, string serviceDescription) { // Initialise the Global log4net properties so we can use them for log file names and logging when required. log4net.GlobalContext.Properties["custom-assembly"] = System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location); log4net.GlobalContext.Properties["custom-processname"] = System.Diagnostics.Process.GetCurrentProcess().ProcessName; log4net.GlobalContext.Properties["custom-process-id"] = System.Diagnostics.Process.GetCurrentProcess().Id; // WOULD LIKE ACCESS TO THE SERVICE INSTANCE NAME HERE var logFileInfo = new System.IO.FileInfo(".\\Log.config"); log4net.Config.XmlConfigurator.Configure(logFileInfo); var host = HostFactory.New(r => { var controller = controllerFactory(); r.Service<ConsumerService>( () => new ConsumerService(controller)); r.SetServiceName(serviceName); r.SetDescription(serviceDescription + " © XYZ Ltd. 2012"); r.SetDisplayName(serviceDescription + " © XYZ Ltd. 2012"); r.StartAutomatically(); r.EnablePauseAndContinue(); r.RunAsLocalSystem(); }); return host.Run(); } 
+4
source share
2 answers

The instance name is passed on the command line, you can access the command line arguments and pull them out of there. This may be slightly corrected, but if you look at ServiceInstaller, you will see how we configure the path to the command by editing the registry after installing the service.

+3
source

HostSettings are passed to the factory service, which contains the InstanceName property as a property. You must use this to initialize the log application that you want to add to log4net .

+4
source

Source: https://habr.com/ru/post/1435054/


All Articles