Pavan Kumar
Pavan Kumar

Reputation: 85

Use Nlog to log context info of Asp.Net Web API

I've two separate tables to log user activity and errors in asp.net web Api. Here's my Activity Log table: ActivityLog

To store the Log information in the table, Here's the Nlog.config setting.

<target name="database" xsi:type="Database" keepConnection="true" useTransactions="true"
             dbProvider="System.Data.SqlClient" commandType="Text"
        connectionString="data source=XXXXX;initial catalog=XXXXX;integrated security=false;persist security info=True;User ID=XXXXX;Password=XXXXX"
        commandText="INSERT INTO [dbo].[ActivityLog]([PageName],[MethodName],[IPAddress],[RequestedUrl],[IsAuthenticated],[UserName],[Date]) VALUES(@PageName,@MethodName,@IPAddress,@RequestedUrl,@IsAuthenticated,@UserName,@Date)">
  <parameter name="@PageName" layout="" />
  <parameter name="@MethodName" layout="" />
  <parameter name="@IPAddress" layout=""/>
  <parameter name="@RequestedUrl" layout="${aspnet-request:serverVariable=HTTP_URL}"/>
  <parameter name="@IsAuthenticated" layout="${aspnet-user-identity}:isAuthenticated"/>
  <parameter name="@UserName" layout="${aspnet-user-identity}"/>
  <parameter name="@Date" layout="${date:s}"/>
</target>

For the Page Name parameter I need the Web API Controller Name, and for Method Name parameter I need the action Method of the Controller that is called. Also I need to know whether the user is authenticated or not.

Now Kindly let me know the settings defined in the Nlog config file are correct or not and also how to pass values to the other parameters.

Upvotes: 1

Views: 2304

Answers (1)

Julian
Julian

Reputation: 36830

All possible layout renderers could be found here. You could use the following renderers:

  • Web API Controller Name: ${aspnet-MVC-Controller}
  • Method Name: you could use the ${callsite} or ${aspnet-mvc-action}
  • isAuthenticated: ${identity:isAuthenticated}

PS:

  • All parameters to the database target are string parameters

Upvotes: 2

Related Questions