我的日志记录有问题。我有一个类用于在我的 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