vb.net 日志类

这个博客介绍了一个名为`Logger`的VB.NET类,用于实现自定义的日志记录和错误处理功能。该类能够创建按日期和小时区分的日志文件,并自动创建日志目录。日志信息包含时间、源文件位置和具体日志内容,同时在调试窗口中输出。错误日志和普通日志分别保存在不同的文件夹下,方便分类查看。
摘要由CSDN通过智能技术生成
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

同时会在调试窗口输出

日志内容为:日志发生时间        日志产生在哪个源文件的哪一行        日志具体内容

一个小时一个日志文件

日志目录会自动创建

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值