【问题标题】:I'd like to use the Topshelf instance name as part of the log4net log file name我想使用 Topshelf 实例名称作为 log4net 日志文件名的一部分
【发布时间】:2012-12-02 11:50:20
【问题描述】:

使用 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();
}

【问题讨论】:

    标签: log4net topshelf


    【解决方案1】:

    HostSettings 被传递到服务工厂,其中包含 InstanceName 作为属性。您应该使用它来初始化要添加到 log4net 的日志附加程序。

    【讨论】:

    • 添加一点细节...... HostSettings 被传递给 ServiceConfigurator 上的“ConstructUsing”方法。你可能会有这样的代码:` x.Service(sc => { sc.ConstructUsing(hostSettings => new ServiceRunner(hostSettings)); `
    【解决方案2】:

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

    【讨论】:

    • 谢谢特拉维斯;我会试一试,看看效果如何。
    • 嗨,特拉维斯;效果很好,谢谢。我可以从命令行解析实例名称的命令行。再次感谢您的专业知识。
    • 没问题,有问题也可以打邮件列表。 groups.google.com/forum/#!forum/topshelf-discuss
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    相关资源
    最近更新 更多