web.configにNlog設定を踏襲し、変換構文を使ってソリューション構成ごとに異なるログ設定をする

アクション
最初に以下を宣言する。
これで、ソースコードにはログを貼るだけでよくなる。
  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
  </configSections>

あとは、targetとruleを付けるだけ。
全体像は以下の通り。

Web.config
<configuration>
  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
  </configSections>
  <nlog>
    <targets>
      <target name="logFile" type="File" fileName="./logs/${shortdate}-debug.log" encoding="UTF-8"
        archiveFileName="${basedir}/logs/archives/archive.${shortdate}-debug.log" archiveEvery="Day" archiveNumbering="Rolling" maxArchiveFiles="365"
        layout="${longdate},${uppercase:${level}},${callsite},${callsite-linenumber},${message}"/>
      <!--
      <target name="asException" type="FilteringWrapper" condition="length('${exception}')&gt;0">
            <target type="File" fileName="./logs/${shortdate}-trace.log" layout="${ExceptionVerboseLayout}"/>
        </target>
        -->
      <target type="Debugger" name="debugger" layout="${longdate} ${uppercase:${level}}|${callsite}|${callsite-linenumber}|${message}|${stacktrace}"/>
    </targets>
    <rules>
      <logger name="*" minlevel="Trace" writeTo="logFile"/>
      <logger name="*" minlevel="Trace" writeTo="debugger"/>
    </rules>
  </nlog>

次に変換構文
変換箇所を赤文字にしている。
Web.Release.config
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
    <connectionStrings>
        <add name="ConnectionString"
          connectionString="Data Source=127.0.0.1\SQLEXPRESS;Initial Catalog=RELEASE_DB;Connect Timeout=60;Persist Security Info=False; User ID=hoge;Password=1234"
          xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
    </connectionStrings>
    <appSettings>
        <add key="Environment" value="PRODUCTION" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
    </appSettings>
   
    <system.web>
    <!-- Disable Debug Mode -->
    <compilation xdt:Transform="
RemoveAttributes(debug)" />
  </system.web>
  <nlog>
      <targets>
          <target name="logFile"
                  type="File"
                  fileName="./logs/${shortdate}-release.log"
                  encoding="UTF-8"
                  archiveFileName="${basedir}/logs/archives/archive.${shortdate}-release.log"
                  archiveEvery="Day"
                  archiveNumbering="Rolling"
                  maxArchiveFiles="365"
                  layout="${longdate},${uppercase:${level}},${callsite},${callsite-linenumber},${message}"
                  xdt:Transform="SetAttributes"
                  xdt:Locator="Match(name)"

                  />
      </targets>
      <rules>
          <logger name="*" minlevel="Info" writeTo="logFile"
                xdt:Transform="SetAttributes" xdt:Locator="Match(writeTo)"
                  />
      </rules>
  </nlog> 
</configuration>

Classへログを貼るときのサンプルは以下の通り。
namespace WebMVC.Controllers
{
    public class HomeController : Controller
    {
        public static Logger logger = LogManager.GetCurrentClassLogger();

        public ActionResult Index()
        {
            string env = ConfigurationManager.AppSettings["Environment"];
            string webv = "webpages: Version";
       

            logger.Trace("trace log message: env->{0}, webv->{1}", env, webv);
            logger.Debug("debug log message");
            logger.Info("info log message");
            logger.Warn("warn log message");
            logger.Error("error log message");
            logger.Fatal("fatal log message");


            theDbConnection();

            return View();
        }

        private void theDbConnection()
        {
            logger.Info("theDbConnection Start");

            string ConnectionStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            SqlConnection con = new SqlConnection(ConnectionStr);
            con.Open();
            try
            {
                SqlCommand com = new SqlCommand("select * from data", con);
                SqlDataReader sdr = com.ExecuteReader();
                while (sdr.Read() == true)
                {
                    try
                    {
                        logger.Debug(sdr["id"]);
                        logger.Debug(sdr["name"]);
                        logger.Debug(sdr["tttt"]);
                    }
                    catch (Exception e)
                    {
                        logger.Error(e);
                    }
                }
                com.Dispose();
            }
            catch (SqlException exc)
            {
                logger.Error(exc);
            }
            finally
            {
                logger.Info("con.Close");
                con.Close();
                con.Dispose();
            }
            return;

        }
    }
}


コメント

このブログの人気の投稿

ソリューション構成ごとにconfigファイルを作成する

C++の古いプロジェクトのビルドでerror MIDL2311 : statements outside library block are illegal in mktyplib compatability mode

web.config debug/releaseの内容を変換構文を使って切り替える