DCSIMG
Logging Linq to SQL operations - Nati Dobkin
Logging Linq to SQL operations

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);
Published Monday, February 01, 2010 11:33 PM by Nati Dobkin

Comments

# re: Logging Linq to SQL operations@ Friday, February 12, 2010 11:35 AM

I am not sure that this is the best way.

1) logging in real-time will make you app work slow

2) writing to file instead of DB is harder to read\filter

I think that first you should write to DB.

if you can it will even be better thinking of the log as in-memory first and persist to lg table later as bulk.

have fun.

by Shani

# re: Logging Linq to SQL operations@ Sunday, February 27, 2011 3:08 PM

Any ideas why this code would not work for me?

I get the select statement printed out through the console, but when I switch to the log file as proposed here (copy, paste), nothing happens. Well, actually the file gets generated, but nothing is writen into it...

by TB

# re: Logging Linq to SQL operations@ Sunday, February 27, 2011 3:24 PM

OK, I had problems with writting to a file - it turned out I have to call

textWriter.Flush()

after performing any action to actually get the text into a file. Any ideas why this is required? Or is it normal?

by Csharper

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: