I'm trying to log all Database operations in my webapplication.
I have a LOGS class that writes on Database
public partial class LOGS
{
public static int AddLogs(LOGS log)
{
int ret = 0;
try
{
using (var context = new Entities())
{
log.Data = DateTime.Now;
context.LOGS.Add(log);
ret += context.SaveChanges();
}
return ret;
}
catch (Exception ex)
{
string w = ex.Message;
return -1;
}
}
public static void WriteDetailed(string query)
{
if (u == null || u.LOGLevel == 0)
return;
else
{
StackTrace st = new StackTrace();
StackFrame sf = st.GetFrame(1);
if (sf != null)
{
MethodBase currentMethodName = sf.GetMethod();
String metodo = currentMethodName.ReflectedType.FullName + " " + currentMethodName.Name;
LOGS newLog = new LOGS();
newLog.Tipo = "Q";
newLog.TipoLog = metodo;
newLog.Testo = query;
AddLogs(newLog);
}
}
}
}
To log the select operations I the method in this way:
public static List<Agent> GetAgents()
{
try
{
using (var context = new Entities())
{
var entities = (from a in context.Agent
select a);
LOGS.WriteDetailed(entities.ToString());
return entities.ToList();
}
}
catch (Exception ex)
{
LOGS.WriteExceptionLog(ex);
return null;
}
}
but for me it's impossible to log the insert,updates end delete statements
I read that I could use this method
context.Database.Log = msg => LOGS.WriteDetailed(msg);
and I've tryied to use it in this way:
public static bool AddAgent(Agent newAgent)
{
bool ret = true;
using (var context = new Entities())
{
using (var dbContextTransaction = context.Database.BeginTransaction())
{
try
{
newAgent.DateLM = DateTime.Now;
context.Agent.Add(newAgent);
context.Database.Log = msg => LOGS.WriteDetailed(msg);
ret = ret && context.SaveChanges() > 0;
if (ret)
dbContextTransaction.Commit();
else
dbContextTransaction.Rollback();
return ret;
}
catch (Exception ex)
{
LOGS.WriteExceptionLog(ex);
return false;
}
}
}
}
this works but in a strange way: in a single INSERT operation it will pass in the method WriteDetailed 8 times...
- INSERT [dbo].[Agent]([Name], [Active], [UserLM], [DateLM]) VALUES (@0, @1, @2, @3) SELECT [ID_Agent] FROM [dbo].[Agent] WHERE @@ROWCOUNT > 0 AND [ID_Agent] = scope_identity()
- (empty) 3.-- @0: 'a' (Type = AnsiString, Size = 100)
- -- @1: 'True' (Type = Boolean)
- -- @2: '1' (Type = Int32)
- -- @3: '25/08/2017 13:34:16' (Type = DateTime2)
- -- Executing at 25/08/2017 13:46:17 +02:00
-- Completed in 8 ms with result: SqlDataReader
Isn't possible having the complete INSERT Statement at once?