现在的位置: 首页 > 综合 > 正文

利用日志记录所有LINQ的增,删,改解决方案

2012年12月05日 ⁄ 综合 ⁄ 共 1489字 ⁄ 字号 评论关闭

在项目初期部署的时候,如果bug没有被排除干净,但代码部署到客户机上了,那么调试bug会是个问题,一般我们都会在这段时间把日志打开,在日志中将操作过程记录到日志中。为了将所有的增,删,改的操作都记录下来,我们会加入一个数据上下文的分布类,然后重写SubmitChanges方法,以下是我的解决方案:

 

public partial class YourDataContext : System.Data.Linq.DataContext
    {
        
public override void SubmitChanges(ConflictMode failureMode)
        {
            
//记录日志(每天一个文件,记录所有更改sql,日志会存在第一个盘的log文件夹下)
            if (ConfigurationManager.AppSettings["IsTraceLinqLog"].ToString().ToLower()
                
== "true")
            {
                
string directory = Path.Combine(Directory.GetLogicalDrives().First(), "log");
                Directory.CreateDirectory(directory);
                
string logFile = Path.Combine(directory,
                    
"log" + DateTime.Now.ToShortDateString() + ".txt");
                
using (StreamWriter w = File.AppendText(logFile))
                {
                    w.WriteLine(
"发生时间:{0}", DateTime.Now.ToString());
                    w.WriteLine(
"日志内容为:");
                    
this.Log = w;
                    
try
                    {
                        
base.SubmitChanges(failureMode);
                    }
                    
catch (Exception e)
                    {
                        w.WriteLine(e.Message);
                        
throw;
                    }
                    w.WriteLine(
"--------------------------------------------------------------");

                }
            }
            else
            {
                
base.SubmitChanges(failureMode);
            }

        }
    }

抱歉!评论已关闭.