我有以下功能可以进行文本记录,但是我一直都在错误的下方。它不是每次都出现,而是在IIS级别上出现。发生此错误后,IIS Apppool将停止。
发生未处理的异常,进程终止。
应用程序ID:/ LM / W3SVC / 2 / ROOT / OrderHelpDesk
进程ID:81044
异常:System.UnauthorizedAccessException
消息:对路径'\ Ser-file \ ErrorLog \ 2018-09 \ 09_27_2018.txt'的访问被拒绝。
StackTrace:在OrderHelpDesk.DAL.LogMessage(字符串消息) 在OrderHelpDesk.ViewPendingOrderDetails.AutoGenMailToCSRProcessed(Entity objEntity)处 在System.Threading.ExecutionContext.RunInternal(ExecutionContext executeContext,ContextCallback回调,对象状态,布尔类型saveSyncCtx) 在System.Threading.ExecutionContext.Run(ExecutionContext执行上下文,ContextCallback回调,对象状态,布尔类型saveSyncCtx) 在System.Threading.ExecutionContext.Run(ExecutionContext执行上下文,ContextCallback回调,对象状态) 在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();
}
}
答案 0 :(得分:2)
使用已经实现的日志记录库,例如NLog。
如果不能
发生这种情况是因为LogMessage可以同时被多个线程调用。在这种情况下,一个线程将获取日志文件,而另一个线程将获取AccessDenied,并且由于sw为null,所以您的池将崩溃,但是您调用sw.Close()。 使用synchronization primitives和using的结构(或检查sw是否为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);
}
}
}
答案 1 :(得分:0)
这可能是文件/文件夹权限的问题。