crazyTech
crazyTech

Reputation: 1477

Using a Lock Within Catch for Exception in order to write to Physical log file

My team is working on a C# ASP.NET Web application. I decided to handle errors by writing to an error log file.

The log.Error method that I wrote would log to a physical log file in an error directory.

I thought it would be appropriate to use a lock in order to control threads when it comes to executing the log.Error method because I want to log the error every time it occurs.

Therefore here is the format for most of my exception handling:

protected void blahblahCsharpMethodBlahBlah()
{
try
{
    blah blah C# code blah blah
}
catch(Exception ex  ){
    lock (_objectblahblahCsharpMethodBlahBlah)
    {
        // The following log.Error method that I wrote would log to a physical log file in an error directory.
        log.Error(ex.ToString(),
                  PerlsPivotErrorDirectory,
                  System.Reflection.MethodBase.GetCurrentMethod().Name,
                  this.GetType().Name,    System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location));
}
}
} // protected void blahblahCsharpMethodBlahBlah()

Is it proper practice to use a lock in order to control threads so that they execute the log.Error method in a proper serialized manner?

Upvotes: 1

Views: 242

Answers (1)

esskar
esskar

Reputation: 10940

if you want to ensure thread-safety, you need to use locks. but to make it simpler and more bullet-proof to use, i would lock inside of the Error method. normally you share the same log object (or at least the same log file) between different classes in your application, so it makes more sense to log in your logging (here Error) functions directly.

but you do not want or need to reinvent the wheel. Use NLog which is thread-safe by default.

Upvotes: 4

Related Questions