Custom Logging with Personal Fields in Nlog

Setting the database string via
var databaseTarget = (DatabaseTarget)LogManager.Configuration.FindTargetByName("database");
databaseTarget.ConnectionString = connectionString;
The above didn't work but I used the example below where I set it via the the start of the program.

var defaultConnection = Configuration.GetConnectionString("DefaultConnection");
NLog.GlobalDiagnosticsContext.Set("defaultConnection", defaultConnection);
var logger = LogManager.LoadConfiguration("nlog.config").GetCurrentClassLogger();
Then you can use ${gdc:item=defaultConnection} in your nlog.config:
<target xsi:type="Database" connectionString="${gdc:item=defaultConnection}" />
Rather than using GDC, which is for global static data and fails on concurrent logging, it is better to use EventProperties-Layout-Renderer that allows to pass custom  properties specific for the event

The easiest way of overriding connection string is through the use of GDC:
<target name="db" type="Database" connectionString="${gdc:myConnectionstring}" ... />
Now in your code you can simply do:
GDC.Set("myConnectionString", "Server=.;database=.....");
For Custom Logging with the following...
LogEventInfo theEvent = new LogEventInfo(logLevel, "", message);
theEvent.Properties["OrderId"] =orderId;`


... and in your NLog.config file: 
${event-context:item=OrderId}  -- obsolete
${event-properties:item=OrderId} -- renders OrderId
<nlog throwExceptions="true" xmlns="" xmlns:xsi="">
      <target name="default" xsi:type="File" fileName="logs/app-log.txt" archiveFileName="logs/archives/app-log.{#}.txt" archiveEvery="Day" archiveNumbering="Rolling" maxArchiveFiles="7" />
      <target name="database" xsi:type="Database" dbProvider="System.Data.SqlClient"
        commandText="INSERT INTO [dbo].[AppLog] 
        ([database_name],[app_name], [version], [message_type], [message], [routine], [src_file], [src_line], [username], [computer_name])                   VALUES                                       ('300', @app_name, @version, @message_type,  @message, @routine , @src_file, @src_line, @username, @computer_name)">
        <parameter name="@app_name" layout="${processname}" />
        <parameter name="@version" layout="${assembly-version}" />
        <parameter name="@message_type" layout="${level}" />
        <parameter name="@message" layout="${message}" />
        <parameter name="@routine" layout="${callsite:className=true:includeSourcePath=true:methodName=true}" />
        <parameter name="@src_file" layout="${currentdir}" />
        <parameter name="@src_line" layout="${callsite-linenumber}" />
        <parameter name="@username" layout="${environment-user}" />
        <parameter name="@computer_name" layout="${machinename}" />
      <logger name="*" writeTo="database" />
Doing the rest...
  1.         <target name="eventlog" xsi:type="EventLog" layout="${message}" log="Application" source=" My Custom Api Services" />  
  2.         <target name="database" type="Database" connectionString="Data Source=your sql source;initial catalog=YourDbNameDb;user id=u1;password=p1;MultipleActiveResultSets=True;">  
  3. <rules>  
  4.         <!-- I am adding my 3 logging rules here -->  
  5.         <logger name="*" minlevel="Debug" writeTo="database" />  
  6.         <logger name="*" minlevel="Trace" writeTo="logfile" />  
  7.         <logger name="*" minlevel="Trace" writeTo="eventlog" />  
  8.     </rules>  


Popular posts from this blog

Nginx Best Practices Extended

Installing Windows on Acer chromebook 15 cb3-532

Entity Framework: ToListAynsc & WhereAsync