我遇到了日志问题。我有一个类用于将我的ASP.net应用程序中的事件记录到文本文件中。这个班似乎很好。然而,出现了并发症,因为我们正在使用负载均衡器。我们在两台服务器上运行我们的应用如果一台服务器出现故障,负载均衡器会将Web应用程序切换到另一台服务器。我还可以指示浏览器指定要在哪个服务器上查看应用程序。
问题是,当我转到一台服务器时,应用程序可以正常登录。但是,如果我尝试切换到其他服务器,我会收到此错误:
异常详细信息:System.UnauthorizedAccessException:访问路径' \ myServer-qa \ plantshare \ someFolder \ myApp \ Logs \ 2012_12_14.txt'被拒绝。
ASP.NET无权访问所请求的资源。考虑 授予对ASP.NET请求的资源访问权限 身份。 ASP.NET具有基本进程标识(通常是 IIS 5上的{MACHINE} \ ASPNET或IIS 6上的网络服务)如果使用的话 该申请不是冒充。如果申请是 冒充通过,身份将是 匿名用户(通常是IUSR_MACHINENAME)或经过身份验证的用户 请求用户。
要授予对文件的ASP.NET访问权限,请在资源管理器中右键单击该文件, 选择"属性"并选择“安全”选项卡。点击"添加"加上 适当的用户或组。突出显示ASP.NET帐户,和 选中所需访问的框。
如果我删除了文件,那么服务器首先创建它就会没问题但另一个会失败。如果我检查文件权限,则只有创建它的服务器才有权限。这是我的代码或IIS的问题吗?另外,我们使用Windows身份验证。这是我用来写的课程:
Imports System.Net
Imports System.IO
Public Class logger
Private Shared _thisInstance As logger
Private Shared InstanceLock As New Object
Private Shared FileLock As New Object
Private _path As String
Public Property path() As String
Get
Return _path
End Get
Set(ByVal value As String)
_path = value
End Set
End Property
Protected Sub New(ByVal path As String)
Me.path = path
End Sub
Public Shared Function GetSingleton(ByVal path As String) As logger
SyncLock InstanceLock
If _thisInstance Is Nothing Then
_thisInstance = New logger(path)
End If
End SyncLock
Return _thisInstance
End Function
Private Function checkDir(ByVal path As String) As Boolean
Dim dir As New DirectoryInfo(path)
Dim exist As Boolean = True
If Not dir.Exists Then
Try
dir.Create()
Catch ex As Exception
exist = False
End Try
End If
Return exist
End Function
Private Function checkFile(ByVal path As String) As Boolean
Dim myFile As New FileInfo(path)
Dim exist As Boolean = True
Dim objWriter As IO.StreamWriter
Dim fs As FileStream
If Not myFile.Exists Then
Try
fs = New FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite)
objWriter = New System.IO.StreamWriter(fs)
objWriter.Close()
objWriter.Dispose()
fs.Close()
fs.Dispose()
Catch ex As Exception
exist = False
Finally
End Try
End If
Return exist
End Function
'updates file
Public Sub Logger(ByVal filePath As String, ByVal Message As String, ByVal title As String, Optional ByVal stkTrace As String = "")
Dim sw As StreamWriter
Dim fs As FileStream
Dim path As String
Dim now As DateTime = DateTime.Now
Dim today As String
today = Date.Now.ToString("yyy/MM/dd")
path = Me.path & today.Replace("/", "_") & ".txt"
If checkFile(path) Then
SyncLock FileLock
fs = New FileStream(path, FileMode.Append)
sw = New StreamWriter(fs)
Try
sw.WriteLine("Title: " & title)
sw.WriteLine("Message: " & Message)
sw.WriteLine("StackTrace: " & stkTrace)
sw.WriteLine("Date/Time: " & now.ToString("yyyy/MM/dd HH:mm:ss"))
sw.WriteLine("================================================")
sw.Flush()
Catch ex As Exception
Throw
Finally
sw.Close()
fs.Close()
sw.Dispose()
fs.Dispose()
End Try
End SyncLock
End If
End Sub
End Class