Linq to SQL provide build in logger that logs all select, insert, update and delete operations, it executes. Very helpful tool when something goes wrong.
You can find it under DataContext .Log property that takes TextWriter .
Most of the samples you probably would find about the logger are setting the Console.Out to it, like this:
DataContext dataContext = newMyDataContext(); dataContext.Log = Console.Out;
The more common scenario would be to write it to a text file. Changing this code to open a StreamWriter is not so hand:
string logFilePath = @"c:\log.txt"; FileStream fileStream = new FileStream(logFilePath, FileMode.OpenOrCreate, FileAccess.Write); TextWriter textWriter = new StreamWriter(fileStream); dataContext.Log = textWriter;
Unfortunately this code will not work properly all the time, not if you use Linq to SQL with Async calls or Parallel execution. If you have more then one thread that accessing the same file you probably get the exception "The process cannot access the file because it is being used by another process".
To overcome this problem all that need to be done is opening the file with sharing, using FileShare enum, which is the proper way to handle files when running multi threads
FileStream fileStream = new FileStream(logFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);