Override Connectionstring at NLog Config Setting

2015/5/12 min read
bookmark this
Responsive image

You can define log to database at NLog, but you can't change connection string depend on your enviroment. This blog shows how to change connectionstring at C# side depend on your enviroment.


<?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">

  <!-- 
  See http://nlog-project.org/wiki/Configuration_file 
  for information on customizing logging rules and outputs.
   -->
  <variable name="logDir" value="${specialfolder:folder=ApplicationData}/Log/"></variable>
  <variable name="logFormat" value="${longdate} ${callsite} ${level} ${stacktrace} ${message}"></variable>
  <targets>
    <target xsi:type="File" name="file" fileName="${logDir}/${shortdate}.log" layout="${longdate} ${uppercase:${level}} ${message} ${exception:format=tostring}" maxArchiveFiles="1" archiveAboveSize="1000000"/>
    <target name="database" type="Database"> 
      <connectionString> 
        Data Source=databaseservername;Initial Catalog=databasename;User Id=username;Password=password; 
      </connectionString> 
      <commandText> 
        insert into YourTableForLogging(date,level,message,machine_name, user_name, call_site,thread, exception, stacktrace) values(@time_stamp, @level, @message,@machinename, @user_name, @call_site, @threadid, @log_exception, @stacktrace); 
      </commandText> 
      <parameter name="@time_stamp" layout="${longdate}"/> 
      <parameter name="@level" layout="${level}"/> 
      <parameter name="@message" layout="${message}"/> 
      <parameter name="@machinename" layout="${machinename}"/> 
      <parameter name="@user_name" layout="${windows-identity:domain=true}"/> 
      <parameter name="@call_site" layout="${callsite:filename=true}"/>
      <parameter name="@threadid" layout="${threadid}"/> 
      <parameter name="@log_exception" layout="${exception}"/> 
      <parameter name="@stacktrace" layout="${exception:stacktrace}"/>
    </target>
	 <target name="sendEmail" xsi:type="MethodCall" className="yourClassForSendingEmalNamespace, thisClassAssemblyName" methodName="MethodToSendEmail">
		<parameter layout="${level}" />
		 <parameter layout="${message}" />
		 <parameter layout="${machinename}" />
		 <parameter layout="${exception}" />
		 <parameter name="stacktrace" layout="${exception:format=tostring}" />
	</target>
  </targets>

  <rules>
    <!-- add your logging rules here -->
<logger name="*" minlevel="Debug" writeTo="file" />
<logger name="*" minlevel="Info" appendTo="database"/> 
<logger name="*" minlevel="Fatal" writeTo="sendEmail" />

  </rules>
</nlog>

Following is code to dynamic change connection string defined at NLog.


   using (var databaseTarget = (DatabaseTarget)LogManager.Configuration.FindTargetByName("database"))
                {
                    var entityFrameworkConnection = ConfigurationManager.ConnectionStrings["MyDatabaseName"].ConnectionString;
                    var builder = new EntityConnectionStringBuilder(entityFrameworkConnection);
                    var connectionString = builder.ProviderConnectionString;
                    databaseTarget.ConnectionString = connectionString;
                }