【Tips】構成ファイルから TraceSource の名前を動的に取得する方法 [.NET Framework]
.NET Framework でロギングを行うのに重宝するのが TraceSource です。
通常は構成ファイルに記述した名前をコンストラクターに渡してインスタンスを作るんですが、トレースソース名の指定にリテラル文字列を使いたくないので、構成ファイルから動的に名前を取ってみました。
以下、そのソースです。
// get TraceSource name(s) from Configuration File.
Func<IEnumerable<string>> tsnames = () =>
{
ConfigurationSection section =
(ConfigurationSection)
ConfigurationManager.GetSection("system.diagnostics");
PropertyInformation sources =
section.ElementInformation.Properties["sources"];
ConfigurationElementCollection elems =
(ConfigurationElementCollection)sources.Value;
return from ConfigurationElement elem in elems
select (string)elem.ElementInformation.Properties["name"].Value;
};
このようにしておくと、ローカル上で完結できるので、クラスの中を汚さずに済みます。
また、戻り値を IEnumerable<string> にしておくと、実際に TraceSource のインスタンスを作成するときに楽ができます。
Collection<TraceSource> tss = new Collection<TraceSource>();
foreach (string tsname in tsnames()) tss.Add(new TraceSource(tsname));
上記は Windows.Forms ですが、Web にも流用できます。
素人の理解です
Configからgetして、Configに戻る…完結
なんですねw
ご無沙汰しております^_^
by One-for-you (2014-02-24 22:28)