Wednesday, 12 September 2012

Nlogger configuration file example


 I have put together, small sample of configuration file for you to see how you can specify different types of logging.
In this example I have logging into txt file, database, and event log.



here is the example


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


  <variable name="applicationName" value="Dummmy" />


  <!-- do not change -->
  <variable name="eventLogTaget" value="CompanyName" />

  <targets>
    <!-- NLogViewer logger -->
    <!-- Text file logger
   
<target xsi:type="File" name="log" fileName="${basedir}/${shortdate}.log" layout="${longdate} ${uppercase:${level}} ${message} ${exception:format=ToString,StackTrace}${newline}" />
-->
    <!--
    working
    <target name="eventlog" xsi:type="EventLog"
            layout="${logger}: ${message} ${exception:format=ToString}"
            log="${eventLogTaget}" source="${applicationName}" />-->

  

    
    
    <target name="databaseLog" type="Database">
      <dbprovider>mssql</dbprovider>
      <dbhost>Server</dbhost>
      <dbdatabase>Database</dbdatabase>
      <dbusername>UserName</dbusername>
      <dbpassword>Password</dbpassword>
      <commandText>
        INSERT INTO dbo.ActivityLog([Level],[Logger],[Message],[Exception],[StackTrace])
        VALUES( @level, @logger, @message, @exception, @stacktrace);
      </commandText>
      <parameter name="@level" layout="${level}" />
      <parameter name="@logger" layout="${logger}" />
      <parameter name="@message" layout="${message}" />
      <parameter name="@exception" layout="${exception:format=ToString,StackTrace}${newline}" />
      <parameter name="@stacktrace" layout="${stacktrace}"/>
    </target>
  </targets>
 
  <rules>
    <logger name="*" writeTo="databaseLog" />
  </rules>

  </targets>
  <rules>
    <logger name="*" levels="Trace, Info, Debug, Warn, Error, Fatal" writeTo="log"/>
    <logger name="*" levels="Trace, Info, Debug, Warn, Error, Fatal" writeTo="eventlog"/>
    <logger name="*" levels="Trace, Info, Debug, Warn, Error, Fatal" writeTo="databaseLog"/>
  </rules>
</nlog>


 Errors with configuration?

Now do you have any problems with configuration of NLog and do not want what is wrong?

add following line into your configuration file:
 throwExceptions="true" internalLogFile="c:\nlog.txt" internalLogLevel="Debug"

The full header:
<?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" throwExceptions="true" internalLogFile="c:\nlog.txt" internalLogLevel="Debug">