2016-04-01 1 views
2

NLogのメールターゲット経由で致命的なエラーが発生した場合に、電子メールを送信したいと考えています。 web.configのsystem.net/mailSettings/smtpも設定済みです。NLogのメールターゲットでsystem.net/mailSettings/smtpの 'from'アドレスを使用する方法はありますか?

useSystemNetMailSettings="true"と設定すると、NLogは 'from'アドレス以外のsystem.net /mailSettings/smtpのすべてを使用します。だから私はそれを特にメールのターゲットにもう一度指定する必要があります。

私は何をしましたか?私は変数 "MailFrom"を作成し、アプリケーションの起動時にプログラムで初期化しました。

<nlog> 
    <variable name="MailFrom" value=""/> 
    <targets> 
     <target name="mail" type="Mail" from="${var:MailFrom}" html="false" subject="Subject" to="ToList" useSystemNetMailSettings="true"/> 
    </targets> 
</nlog> 
var section = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection; 
if (section != null) 
    LogManager.Configuration.Variables["MailFrom"] = section.From; 

多分あなたはこれを行うには、いくつかのより良い方法を知っていますか?ありがとう。

答えて

0

このオプションはNLog 4.3.2に追加されました。


PS:きれいな方法はFindTargetByNameを使用することです:

var section = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection; 
if (section != null) 
{ 

    var mailtarget = LogManager.Configuration.FindTargetByName<MailTarget>("mail"); 
    if (mailtarget != null) 
     mailtarget.From = section.From; 
} 
+0

感謝。いいね。ターゲットを取得するときに、MailTargetの代わりにAsyncTargetWrapperを使用するだけです。 var target = LogManager.Configuration.FindTargetByName ( "mail"); var mailtarget = target.WrappedTarget as MailTarget; – dimrun

関連する問題