NLog - config ファイルで variable を使って変数を定義する
ちょっとしたツールのログ出力に NLog を使ってみたときのメモです。
NLog の config ファイルでは、variable 要素を使うと変数を定義できます。
<variable name="sample" value="値" />
定義した変数は、${変数名}
(この場合は${sample}
)と書くことで参照できます。
例えば、ファイルとコンソールに同じレイアウトのログを出力したい場合は、次のように書けます。
<?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <!-- 変数 sample でレイアウトを定義 --> <variable name="sample" value="${longdate}|${level}|${message}" /> <!-- target の layout 属性で変数 sample を参照 --> <targets> <target name="file" xsi:type="File" encoding="utf-8" fileName="${basedir}/Log/${shortdate}.log" layout="${sample}" /> <target name="console" xsi:type="Console" layout="${sample}" /> </targets> <rules> <logger name="*" minlevel="Info" writeTo="file, console" /> </rules> </nlog>
variable 便利ですね。
あと、NLog のドキュメントは上手くまとまっていて調べやすかったですね。