我想使用Topshelf实例名称作为log4net日志文件名的一部分

Big*_*toe 5 log4net topshelf

当使用TopShelf创建服务实例时,我希望能够访问服务实例名称(在安装期间可能已在命令行上设置为服务;这意味着我无法直接访问它)能够将其用作Log4Net中日志文件名的属性.

在下面的示例代码中,我们设置了可用于登录全局上下文的各种属性.我也希望能够在这里设置服务实例名称; 但在主机初始化期间似乎无法访问它.

有关如何在运行时使用Topshelf访问服务实例名称值的任何建议.

下面的示例是我们所有服务使用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();
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*son 6

HostSettings被传递到服务厂,其中包含InstanceName的属性.您应该使用它来初始化要添加到的日志追加器log4net.


Tra*_*vis 4

实例名称在命令行上传递,您可以访问命令行参数并从那里提取它。这可能需要一些调整,但是如果您查看 ServiceInstaller,您可以看到我们如何在安装服务后通过注册表编辑来调整命令路径。