Reputation: 1
using System;
using System.Threading.Tasks;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.DirectoryServices;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Diagnostics;
using System.Configuration;
namespace DB_Logger_1
{
/*This method for Logging to DB*/
public class DBLogger
{
private Database dbClient = null;
SqlConnection conn = new SqlConnection();
public void Log(string UserName, int EventID, string Message, TraceEventType Severity, int Priority)
{
conn.ConnectionString = @"Data Source=D-DG2H6BS\MSSQLSERVER2014;Initial Catalog=DummyDB1;User ID=sa;Password=***********;";
conn.Open();
using (DbCommand cmdInsertLog = dbClient.GetStoredProcCommand("LogToDatabase"))
{
try
{
dbClient.AddInParameter(cmdInsertLog, "UserName", DbType.String, UserName);
dbClient.AddInParameter(cmdInsertLog, "EventID", DbType.Int32, EventID);
dbClient.AddInParameter(cmdInsertLog, "Message", DbType.String, Message);
dbClient.AddInParameter(cmdInsertLog, "TraceEventType", DbType.String, Severity);
dbClient.AddInParameter(cmdInsertLog, "Priority", DbType.String, Priority);
dbClient.ExecuteNonQuery(cmdInsertLog);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (cmdInsertLog.Connection.State == ConnectionState.Open)
{
cmdInsertLog.Connection.Close();
}
cmdInsertLog.Dispose();
}
}
}
}
public class EventLogger
{
public void Log(string UserName, int EventID, string Message, TraceEventType Severity, int Priority)
{
LogEntry logEntry = new LogEntry();
logEntry.Title = Message;
logEntry.EventId = EventID;
logEntry.Message = Message;
logEntry.TimeStamp = DateTime.Now;
}
}
}
What is the error here ... Can this code logs the event into the Database and Event Viewer ? Provide me solutions. This logtoDB part may contain errors. I have not checked it yet.Correct errors if any and post me the same or suggest me solutions with this code only.
Upvotes: 0
Views: 645
Reputation: 1100
May be better decision will be use a ready "logger library" like log4net for example ? You can use it easy for MS SQL logging and and Event Viewer.
Here step by step instruction ( or if you know russian - here with screenshots ).
Upvotes: 1