软件运行过程中日志文件的书写

来源:互联网 发布:burpsuite下载ubuntu 编辑:程序博客网 时间:2024/06/07 07:05

某一软件的运行,可能会由于某些原因在某时刻产生运行错误,从而导致程序不能正常运行。问题既然出现了,那么对于维护人员来说就得立刻,马上,quickly去维护软件。在维护人员到达第一现场最先想到的就是去查看软件运行产生的日志文件,因此,在软件中开发一个书写日志文件的模块是至关重要的。

Imports System.IOPublic Class WriteLog    '创建日志文件    Public Shared Sub CreateLogFile()        Try            If Not File.Exists(AppDomain.CurrentDomain.BaseDirectory & "run.log") Then                File.Create(AppDomain.CurrentDomain.BaseDirectory & "run.log")            End If        Catch ex As Exception        End Try    End Sub    '写日志文件    Public Shared Sub WriteIntoLog(ByVal str As String)        CreateLogFile()        Try            Dim fi As New FileInfo(AppDomain.CurrentDomain.BaseDirectory & "run.log")            '判断缓存是否超过20M            If fi.Length > 20 * 1024 * 1024 Then                fi.Delete()                CreateLogFile()            End If            '往日志文件中写信息            Dim sw As StreamWriter = File.AppendText(AppDomain.CurrentDomain.BaseDirectory & "run.log")            sw.WriteLine(DateTime.Now.ToString() & ": " & str)            sw.Flush()            sw.Close()        Catch ex As Exception        End Try    End SubEnd Class

简单介绍几个知识点;

1.File.AppendText:创建一个 StreamWriter,它将 UTF-8 编码文本追加到现有文件或新文件(如果指定文件不存在)。

2.FileInfo:提供创建、复制、删除、移动和打开文件的属性和实例方法,并且帮助创建 FileStream 对象。 此类不能被继承。


0 0