29

.net Windows アプリケーションで app.config を動的にリロードするにはどうすればよいですか? アプリケーションの開始時の値だけに基づいてではなく、ログのオンとオフを動的に切り替える必要があります。

ConfigurationManager.RefreshSection("appSettings") は機能せず、OpenExeConfiguration を使用して構成ファイルを明示的に開いてみましたが、現在の値ではなく、アプリケーションの起動時に常にキャッシュされた値を取得します。

カスタム構成セクションを作成するという回答を受け入れました。補足として、ばかげた間違い - IDE から実行している場合、app.config ファイルを更新して変更を期待しても意味がありません。bin\debug フォルダー内の .exe.config ファイルを変更する必要があります。どっ!

4

10 に答える 10

25

あなたが言う方法であなた自身のセクションを更新することができます:

ConfigurationManager.RefreshSection("yoursection/subsection");

ロギング true/false をセクションに移動するだけで問題ありません。

于 2008-11-07T13:48:58.910 に答える
7

log4Net を使用している場合は、要求されたとおりに実行できます。

log4net 構成設定をプロジェクトapp.configまたはweb.configファイルに追加することは可能ですが、別の構成ファイルに配置することをお勧めします。保守性という明白な利点とは別に、log4net が構成FileSystemWatcherファイルにオブジェクトを配置して、変更を監視し、その設定を動的に更新できるという追加の利点があります。

別の構成ファイルを使用するには、Log4Net.config という名前のファイルをプロジェクトに追加し、次の属性を AssemblyInfo.cs ファイルに追加します。

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

注: Web アプリケーションの場合、これはLog4Net.configWeb ルートに存在することを前提としています。log4net.configプロパティで、ファイルが「出力にコピー」->「常にコピー」としてマークされていることを確認します。

于 2008-11-07T13:52:08.327 に答える
7

以下は、これを置くことができるハックです。これにより、構成がディスクから読み取られます。

構成ファイルを変更モードで保存してから更新するだけで、アプリケーションがディスクからファイルを読み取るようになります。

ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
于 2010-08-31T09:42:16.087 に答える
2

Application.Start(new Form1())WinForms では、アプリケーションが読み込まれる前 ( の前) にapp.config をプログラムで変更できますSystem.XmlSystem.Configuration.ConfigurationManager

string configFile = Application.ExecutablePath + ".config";  //c:\path\exename.exe.config
XmlDocument xdoc = new XmlDocument();
xdoc.Load(configFile);
XmlNode node = xdoc.SelectSingleNode("/configuration/appSettings/add[@key='nodeToChange']/@value");
node.Value = "new value";
File.WriteAllText(setFile, xdoc.InnerXml);
于 2009-04-14T16:55:51.810 に答える
1

この実装は、実行時にログ レベルを変更し、新しいしきい値を app.config (実際には Application.exe.config) に保持するように記述しました。

インターフェース:

internal interface ILoggingConfiguration
{
  void SetLogLevel(string level);

  string GetLogLevel();
}

実装:

internal sealed class LoggingConfigurationImpl : ILoggingConfiguration
{
  #region Members

  private static readonly ILog _logger = 
    ObjectManager.Common.Logger.GetLogger();
  private const string DEFAULT_NAME_SPACE = "Default.Name.Space";

  #endregion

  #region Implementation of ILoggingConfiguration

  public void SetLogLevel(string level)
  {
    Level threshold = Log4NetUtils.ConvertToLevel(level);
    ILoggerRepository[] repositories = LogManager.GetAllRepositories();

    foreach (ILoggerRepository repository in repositories)
    {
      try
      {
        SetLogLevelOnRepository(repository, threshold);
      }
      catch (Exception ex)
      {
        _logger.ErrorFormat("Exception while changing log-level: {0}", ex);
      }
    }
    PersistLogLevel(level);
  }

  public string GetLogLevel()
  {
    ILoggerRepository repository = LogManager.GetRepository();
    Hierarchy hierarchy = (Hierarchy) repository;
    ILogger logger = hierarchy.GetLogger(DEFAULT_NAME_SPACE);
    return ((Logger) logger).Level.DisplayName;
  }

  private void SetLogLevelOnRepository(ILoggerRepository repository,
                                       Level threshold)
  {
    repository.Threshold = threshold;
    Hierarchy hierarchy = (Hierarchy)repository;
    ILogger[] loggers = hierarchy.GetCurrentLoggers();
    foreach (ILogger logger in loggers)
    {
      try
      {
        SetLogLevelOnLogger(threshold, logger);
      }
      catch (Exception ex)
      {
        _logger.ErrorFormat("Exception while changing log-level for 
            logger: {0}{1}{2}", logger, Environment.NewLine, ex);
      }
    }
  }

  private void SetLogLevelOnLogger(Level threshold, ILogger logger)
  {
    ((Logger)logger).Level = threshold;
  }

  private void PersistLogLevel(string level)
  {
    XmlDocument config = new XmlDocument();
    config.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    string xpath =
      String.Format("configuration/log4net/logger[@name='{0}']/level",
        DEFAULT_NAME_SPACE);
    XmlNode rootLoggerNode = config.SelectSingleNode(xpath);

    try
    {
      rootLoggerNode.Attributes["value"].Value = level;
      config.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

      ConfigurationManager.RefreshSection("log4net");
    }
    catch(Exception ex)
    {
      _logger.ErrorFormat("error while persisting new log-level: {0}", ex);
    }
  }

  #endregion
}

ヘルパー クラス Log4NetUtils:

public sealed class Log4NetUtils
{
  private static readonly ILoggerRepository _loggerRepository =
     LoggerManager.GetAllRepositories().First();

  public static Level ConvertToLevel(string level)
  {
    return _loggerRepository.LevelMap[level];
  }
}

XAML コード:

<ComboBox Name="cbxLogLevel" Text="{Binding LogLevel}">
  <ComboBoxItem Content="DEBUG" />
  <ComboBoxItem Content="INFO" />
  <ComboBoxItem Content="WARN" />
  <ComboBoxItem Content="ERROR" />
</ComboBox>
<Button Name="btnChangeLogLevel" 
        Command="{Binding SetLogLevelCommand}"
        CommandParameter="{Binding ElementName=cbxLogLevel, Path=Text}" >
            Change log level
</Button>
于 2011-07-27T07:56:02.613 に答える
0

app.config ではなく、別の XML ファイルを使用することをお勧めします。ファイルの変更を監視し、変更されたときに自動的に再読み込みすることもできます。

于 2008-11-07T13:46:55.593 に答える
0

RefreshSection メソッドを使用してみましたが、次のコード サンプルを使用して動作するようになりました。

class Program
    {
        static void Main(string[] args)
        {
            string value = string.Empty, key = "mySetting";
            Program program = new Program();

            program.GetValue(program, key);
            Console.WriteLine("--------------------------------------------------------------");
            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
        }

        /// <summary>
        /// Gets the value of the specified key from app.config file.
        /// </summary>
        /// <param name="program">The instance of the program.</param>
        /// <param name="key">The key.</param>
        private void GetValue(Program program, string key)
        {
            string value;
            if (ConfigurationManager.AppSettings.AllKeys.Contains(key))
            {
                Console.WriteLine("--------------------------------------------------------------");
                Console.WriteLine("Key found, evaluating value...");
                value = ConfigurationManager.AppSettings[key];
                Console.WriteLine("Value read from app.confg for Key = {0} is {1}", key, value);
                Console.WriteLine("--------------------------------------------------------------");

                //// Update the value
                program.UpdateAppSettings(key, "newValue");
                //// Re-read from config file
                value = ConfigurationManager.AppSettings[key];
                Console.WriteLine("New Value read from app.confg for Key = {0} is {1}", key, value);
            }
            else
            {
                Console.WriteLine("Specified key not found in app.config");
            }
        }

        /// <summary>
        /// Updates the app settings.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        public void UpdateAppSettings(string key, string value)
        {
            Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            if (configuration.AppSettings.Settings.AllKeys.Contains(key))
            {
                configuration.AppSettings.Settings[key].Value = value;
            }

            configuration.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
于 2012-07-11T05:15:43.987 に答える
0

実際に使用する:

Application.restart();

私にとってはかなりうまくいきました。

よろしく

ホルヘ

于 2009-07-29T07:55:04.573 に答える
0

XMLを使用して独自の構成ファイルリーダーを作成しない限り、これを行う方法はないと思います。構成ファイルの設定に基づいてアプリの開始時にログをオンまたはオフにし、プログラムの実行中に動的にオンまたはオフにしないのはなぜですか?

于 2008-11-07T13:46:31.193 に答える
0

これは不可能だとlog4netのドキュメントを読んだと思います。

ファイルシステムウォッチャーで監視できる外部ログファイルにログを記録してみてください

更新: 再び見つかりました.. http://logging.apache.org/log4net/release/manual/configuration.html#.config%20Files

実行時に app.config をリロードする方法はありません。

于 2008-11-07T13:46:35.033 に答える