将就用着的日志记录类

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

 

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

.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(System.AppDomain.CurrentDomain.BaseDirectory, "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 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 AsString, ByVal message AsString)
    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
posted @ 2011-04-30 14:17  祭天  阅读(2157)  评论(6编辑  收藏  举报