文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>将就用着的日志记录类

将就用着的日志记录类

时间:2011-04-30  来源:祭天

工作忙,都没什么时间上来发东西,难得五一放假,放一篇先...

日志记录,在项目开发过程中是必不可少的,有了它,在项目投入动作后,当出现了问题,也能有所记录作为参考。

.Net 中,日志记录的主要开源工具就是 Log4Net 了,不过它却是过于庞大了,在小系统中,也许只需要记录上错误的信息,所以就有了这个自写的类。

Imports System.IO

Public Class Logger
    Private Shared ReadOnly _instance As Logger = New Logger()

    Public Shared ReadOnly Property Instance() As Logger
        Get
            Return _instance
        End Get
    End Property

    Private m_logFolderPath As String

    Private Sub New()
        Me.m_logFolderPath = Path.Combine(Environment.CurrentDirectory, "Logs")
        If (Not Directory.Exists(Me.m_logFolderPath)) Then
            Directory.CreateDirectory(Me.m_logFolderPath)
        End If
    End Sub

    Public Sub [Error](ByVal ex As Exception)
        Dim st As StackTrace = New StackTrace()
        Dim method As System.Reflection.MethodBase = st.GetFrame(1).GetMethod()

        Me.Write(String.Concat(method.DeclaringType.FullName, ".", method.Name), ex.Message)
    End Sub

    Private Sub Write(ByVal source As String, ByVal message As String)
        System.Threading.Monitor.Enter(Me)

        Globals.ErrorMessage = message

        Dim sw As StreamWriter = Nothing
        Dim currTime As Date = Date.Now
        Dim logFilePath = Path.Combine(Me.m_logFolderPath, String.Concat("ex", currTime.ToString("yyyyMM"), ".log"))
        Try
            If (File.Exists(logFilePath)) Then
                sw = File.AppendText(logFilePath)
            Else
                sw = File.CreateText(logFilePath)
            End If

            sw.Write(currTime.ToString("yyyy-MM-dd HH:mm:ss"))
            sw.Write("  ")
            sw.Write(source)
            sw.Write("  ")
            sw.WriteLine(message)
        Finally
            If (sw IsNot Nothing) Then
                sw.Close()
            End If
        End Try

        System.Threading.Monitor.Exit(Me)
    End Sub
End Class

说明:

  1、实用了单例模式,只实例化一次。

  2、为了避免写入日志时目录不存在,所以我在构造函数里进行判断,这样当调用时,目录不存在的话就新建一个。

  3、使用反射获取调用的方法,使开发人员可以知道是哪个方法引发异常。

  4、针对多线程情况,做了加锁处理。

使用方法:

    Public Function Delete(ByVal info As BankInfo) As ExecuteState
        Try
            Dim intResult As Integer = SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionString, CommandType.Text, SQL_DELETE, Me.GetParameters(info, OperateState.Delete))
            If (intResult <= 0) Then
                Return ExecuteState.Fail
            End If

            Return ExecuteState.Success
        Catch ex As Exception
            Logger.Instance.Error(ex)
            Return ExecuteState.Error
        End Try
    End Function
相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载