Imports System.IO
Public Class Logger
Public Shared Function log(str As String, Optional err As Boolean = False) As Boolean
Dim p As String
If (err = True) Then
p = "err"
Else
p = "log"
End If
Dim path As String = Application.StartupPath & "\logs\" & p & "\" & Year(Now) & "-" & Format(Month(Now), "0#") & "-" & Format(Microsoft.VisualBasic.Day(Today), "0#")
wm_mkdir(path)
Dim source_file As String, file_line As Int32
Dim strace As New StackTrace(1, True)
Dim stFrames As StackFrame() = strace.GetFrames()
Dim filename As String
If (err = True) Then
source_file = stFrames(1).GetFileName()
file_line = stFrames(1).GetFileLineNumber
Else
source_file = stFrames(0).GetFileName()
file_line = stFrames(0).GetFileLineNumber
End If
If (source_file <> "") Then
Dim pos As Int32 = source_file.LastIndexOf("\")
filename = Mid(source_file, pos + 2) & " [" & file_line & "行] "
Else
filename = ""
End If
Dim append_result As Boolean = appendFile(path, Now() & vbTab & filename & vbTab & str)
Debug.Print(Now() & vbTab & IIf(err = True, "err", "log") & vbTab & filename & vbTab & str)
Return append_result
End Function
Public Shared Function err(str As String) As Boolean
Return log(str, True)
End Function
Private Shared Function appendFile(Path As String, str As String) As Boolean
Dim sw As StreamWriter = New StreamWriter(Path & "\" & Hour(Now) & ".log", True, System.Text.Encoding.UTF8)
Try
sw.WriteLine(str)
sw.Close()
Return True
Catch ex As Exception
Return False
End Try
End Function
Public Shared Function wm_mkdir(path As String) As Boolean
If Directory.Exists(path) = False Then
If wm_mkdir(Mid(path, 1, path.LastIndexOf("\"))) = False Then
Return False
End If
MkDir(path)
Return True
End If
Return True
End Function
End Class
使用方法:
Logger.log("日志")
Logger.err("发生错误")
日志文件会产生在: 程序所在目录\logs\log\日期\小时.log 和 程序所在目录\\logs\err\日期\小时.log
同时会在调试窗口输出
日志内容为:日志发生时间 日志产生在哪个源文件的哪一行 日志具体内容
一个小时一个日志文件
日志目录会自动创建