J'en ai vu des existantes mais pas assez de fonctionnalité pour ce que je voulais faire...
Donc en instanciant la classe cLog, vous pourrez :
- actirer/désactiver les log dans un repertoire de votre choix (ou dans le repertoire d'install de l'appli) et nommé AAMMJJ_NomAppli.log
- configurer un niveau de log parmis 5 (Normal, Erreur, Warning, Verbose, Debug)
- Supprimer les anciens log plus vieux d'un nombre de jour spécifier en paramètre.
Les contrôles effectué dans la classe :
- suppression des fichiers log vide
- création d'un nouveau fichier log en cas de changement de date (utile pour les service et appli qui tourne 24/24)
- création d'un nouveau fichier log en cas de taille supérieur à 20Mo
Source / Exemple :
'#####################################
'# Logging class - 11/2007
'# v2.0
'#
'# Ex :
'# Dim MyLog As cLog
'# MyLog = New cLog(TRUE, "DEFAULT") 'DEFAULT is set to \ApplicationPath\Logfiles
'# MyLog.Enable()
'# MyLog.Write("Application Started...", cLog.LEVEL._NORMAL)
'# MyLog.SetLevel(cLog.LEVEL._DEBUG) 'To set a different logging level
'# MyLog.EnableFRE(Engine)
'# MyLog = Nothing
'#####################################
Option Strict Off
Option Explicit On
Imports System.IO
Public Class cLog
Enum LEVEL
_ERROR
_WARNING
_NORMAL
_VERBOSE
_DEBUG
End Enum
Private _LogEnabled As Boolean = True
Private _Path As String = ""
Private _Name As String = ""
Private _Stream As StreamWriter
Private _Date As String = Format(Now(), "yyyy/MM/dd")
Private _Level As LEVEL
#Region "Public functions"
'Constructor
Public Sub New(Optional ByVal LogEnabled As Boolean = True, Optional ByVal LogPath As String = "DEFAULT", Optional ByVal Level As LEVEL = LEVEL._NORMAL)
_LogEnabled = LogEnabled
_Level = Level
Try
If (LogPath = "DEFAULT") Then
_Path = My.Application.Info.DirectoryPath & "\Logfiles\"
Else
_Path = LogPath & "\"
End If
If Not Directory.Exists(_Path) Then Directory.CreateDirectory(_Path)
Catch ex As Exception
MsgBox("cLog class / function New(): " & ex.Message.ToString, MsgBoxStyle.Critical)
End Try
End Sub
'Write in the log
Public Sub Write(ByRef sMessage As String, Optional ByRef LogLevel As LEVEL = LEVEL._NORMAL)
If _LogEnabled = True Then
If _Stream Is Nothing Then InitializeStream()
SetLogfile()
Select Case LogLevel
Case LEVEL._NORMAL 'normal
sMessage = "[NORMAL ] " & sMessage
Case LEVEL._ERROR 'error
sMessage = "[ERROR ] " & sMessage
Case LEVEL._VERBOSE 'verbose
sMessage = "[VERBOSE] " & sMessage
Case LEVEL._WARNING 'warning
sMessage = "[WARNING] " & sMessage
Case LEVEL._DEBUG 'debug
sMessage = "[DEBUG ] " & sMessage
End Select
If LogLevel <= _Level Then _Stream.WriteLine("[" & Format(Now(), "yyyy/MM/dd-HH:mm:ss") & "] " & sMessage)
End If
End Sub
'Deleting logfiles old from X days
Public Sub DeleteOld(Optional ByVal nbDays As Integer = 10)
Dim File As FileInfo
Dim list As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
Dim FilePath As String
Try
list = My.Computer.FileSystem.GetFiles(_Path, FileIO.SearchOption.SearchTopLevelOnly)
For Each FilePath In list
File = New FileInfo(FilePath)
If File.CreationTime.ToString("yyyyMMdd") < Format(DateTime.Now.AddDays(-nbDays), "yyyyMMdd") Then
File.Delete()
End If
Next
Catch ex As Exception
'Logfile can't be delete
Write("Log file can't be deleted: " & ex.Message.ToString, LEVEL._ERROR)
End Try
End Sub
#End Region
#Region "Enable/disable logging"
'Enable application logging
Public Sub Enable()
_LogEnabled = True
End Sub
'Disable application logging
Public Sub Disable()
_LogEnabled = False
End Sub
'Set logging level
Public Sub SetLevel(ByRef Level As LEVEL)
_Level = Level
Write("Log level has been changed due to user settings: " & GetLevel())
End Sub
#End Region
#Region "Ask for any properties and you'll get..."
'Get current log level
Public Function GetLevel() As String
Return _Level.ToString
End Function
'Return the name of the logfile
Public Function GetName() As String
Return _Name
End Function
'Return the path of the logfile
Public Function GetPath() As String
Return _Path
End Function
'Return log file size
Public Function GetSize() As Integer
Dim MyFile As FileInfo
MyFile = New FileInfo(_Path & _Name)
Return MyFile.Length
End Function
#End Region
#Region "Private functions"
'Initialize stream
Private Sub InitializeStream()
Dim Version As String = ""
Try
_Name = Format(Now(), "yyyyMMdd") & "_" & My.Application.Info.AssemblyName & ".log"
_Stream = New StreamWriter(_Path & _Name, True, System.Text.Encoding.Default)
_Stream.AutoFlush = True
Version = "v" & My.Application.Info.Version.Major & "." & My.Application.Info.Version.Minor & "." & My.Application.Info.Version.Build & "." & My.Application.Info.Version.Revision
Write(My.Application.Info.AssemblyName & " " & Version)
Catch ex As Exception
MsgBox("cLog class / function InitializeStream(): " & ex.Message.ToString, MsgBoxStyle.Critical)
End Try
End Sub
'Delete old logfile and create new one if size > 20Mo or day change
Private Sub SetLogfile()
DeleteOld()
Try
'Create a new log if new day or log size > 20Mo
If _Date <> Format(Now(), "yyyy/MM/dd") Or GetSize() > 20000000 Then
_Date = Format(Now(), "yyyy/MM/dd")
If Not _Stream Is Nothing Then
_Stream.Close()
_Stream = Nothing
If GetSize() <> 0 Then
Dim NewName As String = Mid(_Name, 1, Len(_Name) - 4) & "-" & Format(Now(), "hhmmss") & ".log"
My.Computer.FileSystem.MoveFile(_Path & _Name, _Path & NewName)
Else
My.Computer.FileSystem.DeleteFile(_Path & _Name)
End If
InitializeStream()
End If
End If
Catch ex As Exception
MsgBox("cLog class / function SetLogfile(): " & ex.Message.ToString, MsgBoxStyle.Critical)
End Try
End Sub
#End Region
End Class
Conclusion :
Peut être pas tout le temps optimiser mais réaliser dans l'urgence... dsl
Exemple d'utilisation :
Dim MyLog As cLog
MyLog = New cLog(TRUE, "DEFAULT") 'DEFAULT is set to \ApplicationPath\Logfiles
MyLog.Enable()
MyLog.Write("Application Started...", cLog.LEVEL._NORMAL)
MyLog.SetLevel(cLog.LEVEL._DEBUG) 'To set a different logging level
...
MyLog = Nothing
Vous n'êtes pas encore membre ?
inscrivez-vous, c'est gratuit et ça prend moins d'une minute !
Les membres obtiennent plus de réponses que les utilisateurs anonymes.
Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.
Le fait d'être membre vous permet d'avoir des options supplémentaires.