Imports System.IO
''' <summary>
''' 日志类
''' </summary>
Public NotInheritable Class CsDataLog
    ''' <summary>
    ''' 日志类型
    ''' </summary>
    Public Enum LogType
        ''' <summary>堆栈跟踪信息</summary>
        Trace
        ''' <summary>警告信息</summary>
        Warning
        ''' <summary>错误信息应该包含对象名、发生错误点所在的方法名称、具体错误信息</summary>
        [Error]
        ''' <summary>与数据库相关的信息</summary>
        SQL
    End Enum


    ''' <summary>日志文件所在路径</summary>
    Private Shared _logPath = String.Empty

    ''' <summary>日志前缀说明信息</summary>
    Private Shared _logFilePrefix = String.Empty

    ''' <summary>
    ''' 保存日志的文件夹
    ''' </summary>
    Public Shared Property LogPath As String
        Get

            If Equals(_logPath, String.Empty) Then
                _logPath = Application.StartupPath
            End If
            Return _logPath
        End Get
        Set(ByVal value As String)
            _logPath = value
        End Set
    End Property

    ''' <summary>
    ''' 日志文件前缀
    ''' </summary>
    Public Shared Property LogFilePrefix As String
        Get
            Return _logFilePrefix
        End Get
        Set(ByVal value As String)
            _logFilePrefix = value
        End Set
    End Property

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="ex"></param>
    Public Shared Sub WriteErrorLog(ex As Exception)
        Dim msg As String = String.Empty
        msg &= $"ErrorMessage:{ex.Message}{vbNewLine}"
        msg &= $"ErrorTime:{Now}{vbNewLine}"
        msg &= $"ErrorSource:{ex.Source}{vbNewLine}"
        msg &= $"ErrorType:{ex.GetType}{vbNewLine}"
        msg &= $"ErrorTargetSite:{ex.TargetSite}{vbNewLine}"
        msg &= $"ErrorStackTrace:{ex.StackTrace}{vbNewLine}"
        WriteLog(LogType.Error, msg)
    End Sub

    ''' <summary>
    ''' 将信息入到日志
    ''' </summary>
    ''' <param name="logType">日志类型</param>
    ''' <param name="msg">日志内容</param>
    Public Shared Sub WriteLog(ByVal logType As String, ByVal msg As String)
        Dim sw As StreamWriter = Nothing
        Try
            '同一天同一类日志以追加形式保存
            sw = File.AppendText($"{LogPath}{Path.DirectorySeparatorChar}{LogFilePrefix}_{Date.Now:yyyyMMdd}.Log")
            sw.WriteLine(logType & "#" & Date.Now.ToString("yyyy-MM-dd HH:mm:ss: ") & msg)
        Catch
        Finally
            sw.Close()
        End Try
    End Sub

    ''' <summary>
    ''' 写日志
    ''' </summary>
    Public Shared Sub WriteLog(type As LogType, ByVal msg As String)
        WriteLog(type.ToString(), msg)
    End Sub

End Class
