【问题标题】:Is there a way to add %APPDATA% to the Log4Net configuration path in AssemblyInfo.cs?有没有办法将 %APPDATA% 添加到 AssemblyInfo.cs 中的 Log4Net 配置路径?
【发布时间】:2012-08-22 18:56:38
【问题描述】:

我正在配置 log4net 以使用单独的配置文件。这可以通过在您的 AssemblyInfo.cs 文件中添加以下行来完成。

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)]

这个位置是相对于程序目录的,但我希望它在用户的 APPDATA 文件夹中。比如:

ConfigFile = @"C:\Users\UserName\AppData\Roaming\MyApplication\Logging\Log4Net.config"

问题在于这不是相对路径,即不支持不同的用户名等。我真正想要的是以下内容:

ConfigFile = @"%APPDATA%\MyApplication\Logging\Log4Net.config"

这当然行不通。我希望这可以解决它:

ConfigFile = @"${APPDATA}\MyApplication\Logging\Log4Net.config"

或者这个:

ConfigFile = Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
    @"MyApplication\Logging\Log4Net.config")

运气不好。前两个只是认为它是相对路径的一部分,后者被拒绝,因为它在 AssemblyInfo 中:

错误 1 ​​属性参数必须是常量表达式 typeof 属性参数的表达式或数组创建表达式 类型 C:\Source\ ... \Tools\Logging\Logging\Properties\AssemblyInfo.cs 39 56 日志记录

我是否必须将应用程序配置为在启动时使用自定义路径?我真的不想,因为我希望代码尽可能不可知。

【问题讨论】:

    标签: c# .net logging log4net relative-path


    【解决方案1】:

    我最终在启动时执行了配置。在实现我的日志外观时,我刚刚说过:

    class Log4NetLogger : ILogger
    {
        public Log4NetLogger(...)
        {
            if (!m_Configured){
                string configFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"MyApplication\Logging\Log4Net.config");
                log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(configFile));
                m_Configured = true;
            }
            ...
        }
        ...
    }
    

    【讨论】:

    • 我想我也不应该硬编码“MyApplication\Logging\Log4Net.config”路径。
    猜你喜欢
    • 2014-12-08
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-25
    • 2018-11-30
    • 2011-12-24
    相关资源
    最近更新 更多