ASP.NET with NLOG Custom fields with javascript and server logging

 

NLOG is logging package for ASP.NET  you can install package from NUGet

below I am pasting nlog config for inserting custom data in logging

 

<?xml version=”1.0″ encoding=”utf-8″ ?>
<nlog xmlns=”http://www.nlog-project.org/schemas/NLog.xsd&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
autoReload=”true”
internalLogLevel=”Trace”
throwExceptions=”true”
internalLogFile=”${basedir}/internalLog.txt”
internalLogToConsole=”true”>

<!– define various log targets –>
<targets>
<!– write logs to file –>
<target name=”file” xsi:type=”File” fileName=”${basedir}/logs/Log ${shortdate}.txt” layout=”${longdate} ${callsite} ${level}: ${message} ${exception:format=Message,StackTrace} ${stacktrace}” />

<!– write log message to database –>
<target xsi:type=”Database” name=”Logger” keepConnection=”true”
useTransactions=”true”
dbDatabase=”Logger”
commandText=”INSERT INTO LogTable (CreateDate, Origin, LogLevel, Message, Exception, StackTrace,UserId,ActionType) values (@createDate, @origin, @logLevel, @message, @exception, @stackTrace,@UserId,@ActionType)”
connectionString=”Server=LR3TWVSHPQ03;Initial Catalog=12L_Ext_Apps_Dev001_RRRS;User Id=RRRSUser;Password=Y0rHp4eeWpp)t*e303″ >

<parameter name=”@createDate” layout=”${date}”/>
<parameter name=”@origin” layout=”${callsite}”/>
<parameter name=”@logLevel” layout=”${level}”/>
<parameter name=”@message” layout=”${message}”/>
<parameter name=”@exception” layout=”${exception:format=Message,StackTrace}”/>
<parameter name=”@stackTrace” layout=”${stacktrace}”/>
<parameter name=”@UserId” layout=”${event-context:item=UserId}”/>
<parameter name=”@ActionType” layout=”${event-context:item=ActionType}”/>
<!– custom field! –>
<!– custom field! –>

</target>
</targets>
<rules>
<logger name=”*” minlevel=”Trace” writeTo=”file” />
<logger name=”*” minlevel=”Trace” writeTo=”Logger” />
</rules>
</nlog>

 

here is logging table structure

/****** Object:  Table [dbo].[LogTable]    Script Date: 12/17/2013 15:00:11 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[LogTable](
[id] [bigint] IDENTITY(1,1) NOT NULL,
[CreateDate] [datetime] NULL,
[Origin] [nvarchar](50) NULL,
[LogLevel] [text] NULL,
[Message] [text] NULL,
[Exception] [text] NULL,
[StackTrace] [text] NULL,
[UserId] [nvarchar](100) NULL,
[ActionType] [nvarchar](200) NULL,
CONSTRAINT [PK_LogTable] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

 

Here is code to insert log event into table from server code

private Logger logger = LogManager.GetCurrentClassLogger();

LogEventInfo theEvent = new LogEventInfo(NLog.LogLevel.Info, “”, LoginId);
theEvent.Properties[“UserId”] = LoginId;
theEvent.Properties[“ActionType”] = “Portal Login”;
logger.Log(theEvent);

 

I wrote a ajax function with inserts into nlog and then call it in javascript to records client side events

client function

function InsertAction(action)
{
$.ajax({
type: “POST”,
contentType: “application/json; charset=utf-8”,
url: “Search.aspx/SetAction”,
data: “{‘action’:'” + action  + “‘}”,
async :true,
dataType: “json”,

success: function (data) {

},
error: function (result) {
alert(“Error Occurred”);
}
});

 

[WebMethod(EnableSession = true)]
public static object SetAction(string action)
{
Logger logger = LogManager.GetCurrentClassLogger();
try
{

User usr = (User)HttpContext.Current.Session[“User”];

LogEventInfo theEvent = new LogEventInfo(NLog.LogLevel.Info, “”, usr.UserID);
theEvent.Properties[“UserId”] = usr.UserID;
theEvent.Properties[“ActionType”] = action;
logger.Log(theEvent);
}
catch (Exception ex)
{
logger.TraceException(“Exception”, ex);
}
return true;
}

}

 

 

Advertisements