0

I have following function which does text logging but I keep getting below error then and there. Its not coming every time but only sometime and that too at IIS level. IIS Apppool is stopped after this error.

An unhandled exception occurred and the process was terminated.

Application ID: /LM/W3SVC/2/ROOT/OrderHelpDesk

Process ID: 81044

Exception: System.UnauthorizedAccessException

Message: Access to the path '\Ser-file\ErrorLog\2018-09\09_27_2018.txt' is denied.

StackTrace: at OrderHelpDesk.DAL.LogMessage(String Message) at OrderHelpDesk.ViewPendingOrderDetails.AutoGenMailToCSRProcessed(Entity objEntity) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()

public void LogMessage(string Message)
{
     Entity objEntity = new Entity();
     StreamWriter sw = null;

     try            
     {                
         objEntity.LogMessage = string.Format("\r\n{0:MM/dd/yyyy hh:mm:ss tt} : {1}", DateTime.Now, Message);
         objEntity.LogFilePath = ConfigurationManager.AppSettings.Get("ErrorLogPath");
         objEntity.LogFolderName = string.Format("{0:yyyy-MM}", DateTime.Now);
         objEntity.LogFilePath = objEntity.LogFilePath + objEntity.LogFolderName;

         if (!Directory.Exists(objEntity.LogFilePath))
         {
             Directory.CreateDirectory(objEntity.LogFilePath);
         }

         sw = File.AppendText(objEntity.LogFilePath + "\\" + string.Format("{0:MM_dd_yyyy}", DateTime.Now) + ".txt");
         sw.WriteLine(objEntity.LogMessage);
     }
     catch (Exception Ex)
     {
         throw Ex;
     }
     finally
     {
         sw.Close();
     }
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
user3518472
  • 23
  • 1
  • 8
  • 1
    Did you see `'\Ser-file\ErrorLog\2018-09\09_27_2018.txt'` path is correct? also, iis_user has a permission to read/write to that folder? – Just code Sep 28 '18 at 05:10
  • Yes, That path is correct. iis_user has permission for this folder to read and write. The problem is, its not throwing this error every time but occasionally, I don't know under what circumstances can this happen. – user3518472 Sep 28 '18 at 05:14
  • As per your title I think you are getting blank path. – Just code Sep 28 '18 at 05:17
  • If you can, better use a logging library such as Serilog. This problem is already solved, you don't have to re-implement it. – Migg Sep 28 '18 at 05:51

2 Answers2

3

Use already implemented logging libraries like NLog.

if you can't

This happens because LogMessage can be called simultaneously by several threads. In this case one thread will get log file, while the other will get AccessDenied and your pool will crash because sw is null, but you call sw.Close(). Use synchronization primitives and using construction (or check sw for null sw?.Close()):

static object locker = new object();
public void LogMessage(string Message)
{
   lock (locker)
   {
         Entity objEntity = new Entity();                        
         objEntity.LogMessage = string.Format("\r\n{0:MM/dd/yyyy hh:mm:ss tt} : {1}", DateTime.Now, Message);
         objEntity.LogFilePath = ConfigurationManager.AppSettings.Get("ErrorLogPath");
         objEntity.LogFolderName = string.Format("{0:yyyy-MM}", DateTime.Now);
         objEntity.LogFilePath = objEntity.LogFilePath + objEntity.LogFolderName;

         if (!Directory.Exists(objEntity.LogFilePath))
         {
             Directory.CreateDirectory(objEntity.LogFilePath);
         }

         using (StreamWriter sw = File.AppendText(objEntity.LogFilePath + "\\" + string.Format("{0:MM_dd_yyyy}", DateTime.Now) + ".txt"))
         {
             sw.WriteLine(objEntity.LogMessage);
         }  
   }
}
Access Denied
  • 8,723
  • 4
  • 42
  • 72
  • 1
    It also can happen, because another process is locking the file. [Determining the locking process is possible](https://stackoverflow.com/a/20623311/107625). – Uwe Keim Sep 28 '18 at 05:17
  • @UweKeim even though it should not crash IIS pool and I don't think that you need to write complicated logic to determine who is locking. It's better to create another file in that case. – Access Denied Sep 28 '18 at 05:28
  • @Access Denied, Thanks for the answer. For the quick solution I can use above code and for the long term, I can switch for NLog as this will solve all problems related to logging. – user3518472 Sep 28 '18 at 07:28
0

It might be the issue of file/Folder Permission.

Nirav Mistry
  • 949
  • 5
  • 15