Projektdateien hinzufügen.
This commit is contained in:
333
WinLineArtikelnummerGenerator/Modules/ConfigManager.vb
Normal file
333
WinLineArtikelnummerGenerator/Modules/ConfigManager.vb
Normal file
@@ -0,0 +1,333 @@
|
||||
Imports System.IO
|
||||
Imports System.Reflection
|
||||
Imports System.Xml.Serialization
|
||||
Imports DigitalData.Modules.Logging
|
||||
Imports DigitalData.Modules.Config.ConfigAttributes
|
||||
|
||||
Public Class ConfigManager(Of T)
|
||||
Private Const USER_CONFIG_NAME As String = "UserConfig.xml"
|
||||
Private Const COMPUTER_CONFIG_NAME As String = "ComputerConfig.xml"
|
||||
Private Const APP_CONFIG_NAME As String = "AppConfig.xml"
|
||||
|
||||
Private ReadOnly _LogConfig As LogConfig
|
||||
Private ReadOnly _Logger As Logger
|
||||
Private ReadOnly _File As File
|
||||
|
||||
Private ReadOnly _UserDirectory As String
|
||||
Private ReadOnly _UserConfigPath As String
|
||||
Private ReadOnly _ComputerDirectory As String
|
||||
Private ReadOnly _ComputerConfigPath As String
|
||||
Private ReadOnly _AppConfigPath As String
|
||||
Private ReadOnly _AppConfigDirectory As String
|
||||
|
||||
Private ReadOnly _TestMode As Boolean = False
|
||||
|
||||
Private ReadOnly _Blueprint As T
|
||||
Private ReadOnly _BlueprintType As Type
|
||||
Private ReadOnly _Serializer As XmlSerializer
|
||||
|
||||
Private ReadOnly _ExcludedAttributes = New List(Of Type) From {
|
||||
GetType(ConnectionStringAttribute),
|
||||
GetType(ConnectionStringTestAttribute),
|
||||
GetType(GlobalSettingAttribute)
|
||||
}
|
||||
|
||||
Private _WriteAllValuesToUserConfig As Boolean = False
|
||||
|
||||
''' <summary>
|
||||
''' Returns the currently loaded config object
|
||||
''' </summary>
|
||||
''' <returns></returns>
|
||||
Public ReadOnly Property Config As T
|
||||
|
||||
''' <summary>
|
||||
''' Path to the current user config.
|
||||
''' </summary>
|
||||
''' <returns></returns>
|
||||
Public ReadOnly Property UserConfigPath As String
|
||||
Get
|
||||
Return _UserConfigPath
|
||||
End Get
|
||||
End Property
|
||||
|
||||
''' <summary>
|
||||
''' Path to the current computer config. Maybe the same as `UserConfigPath`
|
||||
''' </summary>
|
||||
''' <returns></returns>
|
||||
Public ReadOnly Property ComputerConfigPath As String
|
||||
Get
|
||||
Return _ComputerConfigPath
|
||||
End Get
|
||||
End Property
|
||||
Public ReadOnly Property AppConfigPath As String
|
||||
Get
|
||||
Return _AppConfigPath
|
||||
End Get
|
||||
End Property
|
||||
|
||||
''' <summary>
|
||||
''' Creates a new instance of the ConfigManager
|
||||
''' </summary>
|
||||
''' <seealso cref="ConfigSample"/>
|
||||
''' <param name="LogConfig">LogConfig instance</param>
|
||||
''' <param name="UserConfigPath">The path to check for a user config file, eg. AppData (Usually Application.UserAppDataPath or Application.LocalUserAppDataPath)</param>
|
||||
''' <param name="ComputerConfigPath">The path to check for a computer config file, eg. ProgramData (Usually Application.CommonAppDataPath)</param>
|
||||
''' <param name="ApplicationStartupPath">The path to check for a third config file. This is useful when running the Application in an environment where AppData/ProgramData directories are not available</param>
|
||||
''' <param name="ForceUserConfig">Override values from ComputerConfig with UserConfig</param>
|
||||
Public Sub New(LogConfig As LogConfig, UserConfigPath As String, ComputerConfigPath As String, Optional ApplicationStartupPath As String = "", Optional ForceUserConfig As Boolean = False)
|
||||
_LogConfig = LogConfig
|
||||
_Logger = LogConfig.GetLogger()
|
||||
_File = New File(_LogConfig)
|
||||
|
||||
_Blueprint = Activator.CreateInstance(Of T)
|
||||
_BlueprintType = _Blueprint.GetType
|
||||
_Serializer = New XmlSerializer(_BlueprintType)
|
||||
|
||||
_UserDirectory = _File.CreateDirectory(UserConfigPath)
|
||||
_UserConfigPath = Path.Combine(_UserDirectory, USER_CONFIG_NAME)
|
||||
|
||||
If ComputerConfigPath <> String.Empty Then
|
||||
_ComputerDirectory = _File.CreateDirectory(ComputerConfigPath)
|
||||
_ComputerConfigPath = Path.Combine(_ComputerDirectory, COMPUTER_CONFIG_NAME)
|
||||
End If
|
||||
|
||||
If ApplicationStartupPath <> String.Empty Then
|
||||
_AppConfigPath = Path.Combine(ApplicationStartupPath, APP_CONFIG_NAME)
|
||||
End If
|
||||
|
||||
_WriteAllValuesToUserConfig = ForceUserConfig
|
||||
|
||||
Config = LoadConfig()
|
||||
End Sub
|
||||
|
||||
''' <summary>
|
||||
''' Creates a new ConfigManager with a single (user)config path
|
||||
''' </summary>
|
||||
''' <param name="LogConfig">LogConfig instance</param>
|
||||
''' <param name="ConfigPath">The path to check for a user config file, eg. AppData (Usually Application.UserAppDataPath or Application.LocalUserAppDataPath)</param>
|
||||
Public Sub New(LogConfig As LogConfig, ConfigPath As String)
|
||||
MyClass.New(LogConfig, ConfigPath, String.Empty, String.Empty, ForceUserConfig:=True)
|
||||
End Sub
|
||||
|
||||
''' <summary>
|
||||
''' Save the current config object to `UserConfigPath`
|
||||
''' </summary>
|
||||
''' <param name="ForceAll">Force saving all attributes including the attributes marked as excluded</param>
|
||||
''' <returns>True if save was successful, False otherwise</returns>
|
||||
Public Function Save(Optional ForceAll As Boolean = False) As Boolean
|
||||
Try
|
||||
WriteToFile(Config, _UserConfigPath, ForceAll)
|
||||
Return True
|
||||
Catch ex As Exception
|
||||
_Logger.Error(ex)
|
||||
Return False
|
||||
End Try
|
||||
End Function
|
||||
|
||||
''' <summary>
|
||||
''' Copies all properties from Source to Target, except those who have an attribute
|
||||
''' listed in ExcludedAttributeTypes
|
||||
''' </summary>
|
||||
''' <param name="Source">Source config object</param>
|
||||
''' <param name="Target">Target config object</param>
|
||||
''' <param name="ExcludedAttributeTypes">List of Attribute type to exclude</param>
|
||||
Private Sub CopyValues(Source As T, Target As T, Optional ExcludedAttributeTypes As List(Of Type) = Nothing)
|
||||
Dim oType As Type = GetType(T)
|
||||
Dim oExcludedAttributeTypes = IIf(IsNothing(ExcludedAttributeTypes), New List(Of Type), ExcludedAttributeTypes)
|
||||
Dim oProperties = oType.GetProperties().
|
||||
Where(Function(p)
|
||||
Return p.CanRead And p.CanWrite
|
||||
End Function).
|
||||
Where(Function(p)
|
||||
For Each oAttributeType As Type In oExcludedAttributeTypes
|
||||
If Attribute.IsDefined(p, oAttributeType) Then
|
||||
Return False
|
||||
End If
|
||||
Next
|
||||
Return True
|
||||
End Function)
|
||||
|
||||
For Each oProperty As PropertyInfo In oProperties
|
||||
Dim oValue = oProperty.GetValue(Source, Nothing)
|
||||
If Not IsNothing(oValue) Then
|
||||
oProperty.SetValue(Target, oValue, Nothing)
|
||||
End If
|
||||
Next
|
||||
End Sub
|
||||
|
||||
''' <summary>
|
||||
''' Filters a config object by copying all values except `ExcludedAttributeTypes`
|
||||
''' </summary>
|
||||
''' <param name="Data">Config object</param>
|
||||
''' <param name="ExcludedAttributeTypes">List of Attribute type to exclude</param>
|
||||
''' <returns></returns>
|
||||
Private Function FilterValues(ByVal Data As T, ExcludedAttributeTypes As List(Of Type)) As T
|
||||
Dim oResult As T = Activator.CreateInstance(Of T)
|
||||
|
||||
CopyValues(Data, oResult, ExcludedAttributeTypes)
|
||||
Return oResult
|
||||
End Function
|
||||
|
||||
Private Function LoadConfig() As T
|
||||
' first create an empty/default config object
|
||||
Dim oConfig = Activator.CreateInstance(_BlueprintType)
|
||||
|
||||
' try to load the special app config
|
||||
oConfig = LoadAppConfig(oConfig)
|
||||
|
||||
' try to load the computer config
|
||||
oConfig = LoadComputerConfig(oConfig)
|
||||
|
||||
' now try to load userconfig
|
||||
oConfig = LoadUserConfig(oConfig)
|
||||
Return oConfig
|
||||
End Function
|
||||
|
||||
Private Function LoadAppConfig(ByVal Config As T) As T
|
||||
If Not String.IsNullOrEmpty(_AppConfigPath) AndAlso System.IO.File.Exists(_AppConfigPath) Then
|
||||
Try
|
||||
Dim oAppConfig = ReadFromFile(_AppConfigPath)
|
||||
CopyValues(oAppConfig, Config)
|
||||
Catch ex As Exception
|
||||
_Logger.Error(ex)
|
||||
_Logger.Warn("ApplicationConfig could not be loaded!")
|
||||
End Try
|
||||
_WriteAllValuesToUserConfig = False
|
||||
Else
|
||||
_Logger.Debug("ApplicationConfig does not exist.")
|
||||
_WriteAllValuesToUserConfig = True
|
||||
End If
|
||||
|
||||
Return Config
|
||||
End Function
|
||||
|
||||
Private Function LoadComputerConfig(ByVal Config As T) As T
|
||||
If System.IO.File.Exists(_ComputerConfigPath) Then
|
||||
Try
|
||||
Dim oComputerConfig = ReadFromFile(_ComputerConfigPath)
|
||||
CopyValues(oComputerConfig, Config)
|
||||
Catch ex As Exception
|
||||
_Logger.Error(ex)
|
||||
_Logger.Warn("Computer config could not be loaded!")
|
||||
End Try
|
||||
_WriteAllValuesToUserConfig = False
|
||||
Else
|
||||
_Logger.Debug("Computer config does not exist.")
|
||||
_WriteAllValuesToUserConfig = True
|
||||
End If
|
||||
|
||||
Return Config
|
||||
End Function
|
||||
|
||||
Private Function LoadUserConfig(ByVal Config As T) As T
|
||||
If System.IO.File.Exists(_UserConfigPath) Then
|
||||
Try
|
||||
Dim oUserConfig = ReadFromFile(_UserConfigPath)
|
||||
|
||||
' if user config exists
|
||||
If Not IsNothing(oUserConfig) Then
|
||||
Dim oExcludedAttributes As New List(Of Type)
|
||||
|
||||
' Copy values from user config to final config
|
||||
If _WriteAllValuesToUserConfig Then
|
||||
CopyValues(oUserConfig, Config, New List(Of Type))
|
||||
Else
|
||||
CopyValues(oUserConfig, Config, _ExcludedAttributes)
|
||||
End If
|
||||
End If
|
||||
Catch ex As Exception
|
||||
_Logger.Error(ex)
|
||||
_Logger.Warn("User config could not be loaded!")
|
||||
End Try
|
||||
Else
|
||||
_Logger.Debug("User config does not exist.")
|
||||
End If
|
||||
|
||||
Return Config
|
||||
End Function
|
||||
|
||||
Private Function TestHasAttribute(Config As T, AttributeType As Type) As Boolean
|
||||
For Each oProperty As PropertyInfo In Config.GetType.GetProperties()
|
||||
If Attribute.IsDefined(oProperty, GetType(ConnectionStringAttribute)) Then
|
||||
Return True
|
||||
End If
|
||||
Next
|
||||
|
||||
Return False
|
||||
End Function
|
||||
|
||||
''' <summary>
|
||||
''' Serialize a config object to byte array
|
||||
''' </summary>
|
||||
''' <param name="Data"></param>
|
||||
''' <returns></returns>
|
||||
Private Function Serialize(Data As T) As Byte()
|
||||
Try
|
||||
_Logger.Debug("Serializing config object")
|
||||
|
||||
Using oStream = New MemoryStream()
|
||||
_Serializer.Serialize(oStream, Data)
|
||||
Return oStream.ToArray()
|
||||
End Using
|
||||
Catch ex As Exception
|
||||
_Logger.Error(ex)
|
||||
Throw ex
|
||||
End Try
|
||||
End Function
|
||||
|
||||
''' <summary>
|
||||
''' Write an object to disk as xml
|
||||
''' </summary>
|
||||
''' <param name="Data">The object to write</param>
|
||||
''' <param name="Path">The file name to write to</param>
|
||||
Private Sub WriteToFile(Data As T, Path As String, ForceAll As Boolean)
|
||||
Try
|
||||
_Logger.Debug("Saving config to: {0}", Path)
|
||||
|
||||
' If config was loaded from computer config,
|
||||
' DO NOT save connection string, etc. to user config
|
||||
If _WriteAllValuesToUserConfig = False And ForceAll = False Then
|
||||
Data = FilterValues(Data, _ExcludedAttributes)
|
||||
End If
|
||||
|
||||
Dim oBytes = Serialize(Data)
|
||||
|
||||
Using oFileStream = New FileStream(Path, FileMode.Create, FileAccess.Write)
|
||||
oFileStream.Write(oBytes, 0, oBytes.Length)
|
||||
oFileStream.Flush()
|
||||
End Using
|
||||
Catch ex As Exception
|
||||
_Logger.Warn("Could not save config to {0}", Path)
|
||||
_Logger.Error(ex)
|
||||
Throw ex
|
||||
End Try
|
||||
End Sub
|
||||
|
||||
''' <summary>
|
||||
''' Reads an xml from disk and deserializes to object
|
||||
''' </summary>
|
||||
''' <returns></returns>
|
||||
Private Function ReadFromFile(Path As String) As T
|
||||
Try
|
||||
_Logger.Debug("Loading config from: {0}", Path)
|
||||
Dim oConfig As T
|
||||
|
||||
Using oReader As New StreamReader(Path)
|
||||
oConfig = _Serializer.Deserialize(oReader)
|
||||
End Using
|
||||
|
||||
' If oConfig is Nothing, a config file was created but nothing was written to it.
|
||||
' In this case we need to create oConfig from defaults so we have at least some config object
|
||||
If oConfig Is Nothing Then
|
||||
_Logger.Debug("Config file is valid but empty. Loading default values")
|
||||
oConfig = Activator.CreateInstance(_BlueprintType)
|
||||
End If
|
||||
|
||||
Return oConfig
|
||||
Catch ex As Exception
|
||||
_Logger.Warn("Could not load config from {0}", Path)
|
||||
_Logger.Error(ex)
|
||||
Throw ex
|
||||
End Try
|
||||
End Function
|
||||
End Class
|
||||
267
WinLineArtikelnummerGenerator/Modules/File.vb
Normal file
267
WinLineArtikelnummerGenerator/Modules/File.vb
Normal file
@@ -0,0 +1,267 @@
|
||||
Imports System.IO
|
||||
Imports System.Text.RegularExpressions
|
||||
Imports DigitalData.Modules.Logging
|
||||
|
||||
''' <module>File</module>
|
||||
''' <version>0.0.0.1</version>
|
||||
''' <date>11.10.2018</date>
|
||||
''' <summary>
|
||||
''' Module that provides variouse File operations
|
||||
''' </summary>
|
||||
''' <dependencies>
|
||||
''' NLog, >= 4.5.8
|
||||
''' </dependencies>
|
||||
''' <params>
|
||||
''' LogConfig, DigitalData.Module.Logging.LogConfig
|
||||
''' A LogConfig object
|
||||
''' </params>
|
||||
''' <props>
|
||||
''' </props>
|
||||
''' <example>
|
||||
''' </example>
|
||||
''' <remarks>
|
||||
''' </remarks>
|
||||
Public Class File
|
||||
Private ReadOnly _logger As Logger
|
||||
Private ReadOnly _logConfig As LogConfig
|
||||
|
||||
Private ReadOnly _invalidFilenameChars As String
|
||||
Private ReadOnly _invalidPathChars As String
|
||||
|
||||
Private Const REGEX_CLEAN_FILENAME As String = "[\\/:""<>|\b\0\r\n\t]"
|
||||
Private Const REGEX_CLEAN_PATH As String = "[:""<>|\b\0\r\n\t]"
|
||||
|
||||
Private Const FILE_NAME_ACCESS_TEST = "accessTest.txt"
|
||||
|
||||
Public Sub New(LogConfig As LogConfig)
|
||||
_logConfig = LogConfig
|
||||
_logger = LogConfig.GetLogger()
|
||||
|
||||
_invalidFilenameChars = String.Join("", Path.GetInvalidFileNameChars())
|
||||
_invalidPathChars = String.Join("", Path.GetInvalidPathChars())
|
||||
End Sub
|
||||
|
||||
Public Function GetCleanFilename(FileName As String) As String
|
||||
_logger.Debug("Filename before cleaning: [{0}]", FileName)
|
||||
|
||||
Dim oCleanName As String = FileName
|
||||
oCleanName = Regex.Replace(oCleanName, _invalidFilenameChars, String.Empty)
|
||||
oCleanName = Regex.Replace(oCleanName, REGEX_CLEAN_FILENAME, String.Empty, RegexOptions.Singleline)
|
||||
|
||||
_logger.Debug("Filename after cleaning: [{0}]", oCleanName)
|
||||
|
||||
Return oCleanName
|
||||
End Function
|
||||
|
||||
Public Function GetCleanPath(FilePath As String) As String
|
||||
_logger.Debug("Path before cleaning: [{0}]", FilePath)
|
||||
|
||||
Dim oCleanName As String = FilePath
|
||||
oCleanName = Regex.Replace(oCleanName, _invalidPathChars, String.Empty)
|
||||
oCleanName = Regex.Replace(oCleanName, REGEX_CLEAN_PATH, String.Empty, RegexOptions.Singleline)
|
||||
|
||||
_logger.Debug("Path after cleaning: [{0}]", oCleanName)
|
||||
|
||||
Return oCleanName
|
||||
End Function
|
||||
|
||||
''' <summary>
|
||||
''' Adds fileversions to given filename `Destination` if that file already exists.
|
||||
''' </summary>
|
||||
''' <param name="Destination"></param>
|
||||
''' <returns></returns>
|
||||
Public Function GetVersionedFilename(Destination As String) As String
|
||||
Try
|
||||
Dim oFileName As String = Destination
|
||||
Dim oFinalFileName = oFileName
|
||||
|
||||
Dim oDestinationDir = Path.GetDirectoryName(oFileName)
|
||||
Dim oExtension = Path.GetExtension(oFileName)
|
||||
|
||||
Dim oVersionSeparator As Char = "~"c
|
||||
Dim oFileVersion As Integer = Nothing
|
||||
|
||||
' Split Filename without extension at version separator to:
|
||||
' - Check if file is already versioned
|
||||
' - Get the file version of an already versioned file
|
||||
'
|
||||
' Example:
|
||||
' test1.pdf --> test1 --> ['test1'] --> no fileversion
|
||||
' test1~2.pdf --> test1~2 --> ['test1', '2'] --> version 2
|
||||
' test1~12345~2.pdf --> test1~12345~2 --> ['test1', '12345', '2'] --> still version 2
|
||||
Dim oFileNameWithoutExtension = Path.GetFileNameWithoutExtension(oFileName)
|
||||
Dim oSplitFilename = oFileNameWithoutExtension.Split(oVersionSeparator).ToList()
|
||||
|
||||
' if file is already versioned, extract file version
|
||||
' else just use the filename and set version to 1
|
||||
If oSplitFilename.Count > 1 Then
|
||||
Dim oVersion As Integer = 1
|
||||
Try
|
||||
oVersion = Integer.Parse(oSplitFilename.Last())
|
||||
oFileNameWithoutExtension = String.Join("", oSplitFilename.Take(oSplitFilename.Count - 1))
|
||||
Catch ex As Exception
|
||||
' oFilenameWithoutExtension does NOT change
|
||||
oFileNameWithoutExtension = oFileNameWithoutExtension
|
||||
Finally
|
||||
oFileVersion = oVersion
|
||||
End Try
|
||||
Else
|
||||
oFileVersion = 1
|
||||
End If
|
||||
|
||||
' while file exists, increment version
|
||||
Do
|
||||
oFinalFileName = Path.Combine(oDestinationDir, GetFilenameWithVersion(oFileNameWithoutExtension, oVersionSeparator, oFileVersion, oExtension))
|
||||
_logger.Debug("Intermediate Filename is {0}", oFinalFileName)
|
||||
_logger.Debug("File version: {0}", oFileVersion)
|
||||
oFileVersion += 1
|
||||
Loop While (IO.File.Exists(oFinalFileName))
|
||||
|
||||
_logger.Debug("Final Filename is {0}", oFinalFileName)
|
||||
|
||||
Return oFinalFileName
|
||||
Catch ex As Exception
|
||||
_logger.Warn("Filename {0} could not be versioned. Original filename will be returned!", Destination)
|
||||
_logger.Error(ex)
|
||||
Return Destination
|
||||
End Try
|
||||
End Function
|
||||
|
||||
Private Function GetFilenameWithVersion(FileNameWithoutExtension As String, VersionSeparator As Char, FileVersion As Integer, Extension As String) As String
|
||||
If FileVersion <= 1 Then
|
||||
Return $"{FileNameWithoutExtension}{Extension}"
|
||||
Else
|
||||
Return $"{FileNameWithoutExtension}{VersionSeparator}{FileVersion}{Extension}"
|
||||
End If
|
||||
End Function
|
||||
|
||||
''' <summary>
|
||||
''' Removes files in a directory filtered by filename, extension and last write date
|
||||
''' </summary>
|
||||
''' <param name="Path">The directory in which files will be deleted</param>
|
||||
''' <param name="FileKeepTime">Only delete files which are older than x days. Must be between 0 and 1000 days.</param>
|
||||
''' <param name="FileBaseName">A filename filter which will be checked</param>
|
||||
''' <param name="FileExtension">A file extension which will be checked</param>
|
||||
''' <param name="ContinueOnError">Should the function continue with deleting when a file could not be deleted?</param>
|
||||
''' <returns>True if all files were deleted or if no files were deleted, otherwise false</returns>
|
||||
Public Function RemoveFiles(Path As String, FileKeepTime As Integer, FileBaseName As String, Optional FileExtension As String = "log", Optional ContinueOnError As Boolean = True) As Boolean
|
||||
If Not TestPathIsDirectory(Path) Then
|
||||
Throw New ArgumentException($"Path {Path} is not a directory!")
|
||||
End If
|
||||
|
||||
If Not Directory.Exists(Path) Then
|
||||
Throw New DirectoryNotFoundException($"Path {Path} does not exist!")
|
||||
End If
|
||||
|
||||
If FileKeepTime < 0 Or FileKeepTime > 1000 Then
|
||||
Throw New ArgumentOutOfRangeException("FileKeepTime must be an integer between 0 and 1000!")
|
||||
End If
|
||||
|
||||
Dim oUnableToDeleteCounter = 0
|
||||
Dim oDirectory As New DirectoryInfo(Path)
|
||||
Dim oDateLimit As DateTime = DateTime.Now.AddDays(FileKeepTime)
|
||||
Dim oFiles As List(Of FileInfo) = oDirectory.
|
||||
EnumerateFiles($"*{FileBaseName}*").
|
||||
Where(Function(oFileInfo As FileInfo)
|
||||
Return oFileInfo.Extension = FileExtension And oFileInfo.LastWriteTime < oDateLimit
|
||||
End Function)
|
||||
|
||||
If oFiles.Count = 0 Then
|
||||
_logger.Debug("No files found that match the criterias.")
|
||||
Return True
|
||||
End If
|
||||
|
||||
_logger.Debug("Deleting old files (Found {0}).", oFiles.Count)
|
||||
|
||||
For Each oFile As FileInfo In oFiles
|
||||
Try
|
||||
oFile.Delete()
|
||||
Catch ex As Exception
|
||||
If ContinueOnError = False Then
|
||||
_logger.Warn("Deleting files was aborted at file {0}.", oFile.FullName)
|
||||
Return False
|
||||
End If
|
||||
oUnableToDeleteCounter = oUnableToDeleteCounter + 1
|
||||
_logger.Warn("File {0} could not be deleted!")
|
||||
End Try
|
||||
Next
|
||||
|
||||
If oUnableToDeleteCounter > 0 Then
|
||||
_logger.Debug("Old files partially removed. {0} files could not be removed.", oUnableToDeleteCounter)
|
||||
Else
|
||||
_logger.Debug("Old files removed.")
|
||||
End If
|
||||
|
||||
Return True
|
||||
End Function
|
||||
|
||||
<DebuggerStepThrough>
|
||||
Public Sub MoveTo(FilePath As String, Directory As String)
|
||||
Dim oFileInfo As New FileInfo(FilePath)
|
||||
IO.File.Move(FilePath, Path.Combine(Directory, oFileInfo.Name))
|
||||
End Sub
|
||||
|
||||
<DebuggerStepThrough>
|
||||
Public Sub MoveTo(FilePath As String, NewFileName As String, Directory As String)
|
||||
IO.File.Move(FilePath, Path.Combine(Directory, NewFileName))
|
||||
End Sub
|
||||
|
||||
''' <summary>
|
||||
''' Tries to create a directory and returns its path.
|
||||
''' Returns a temp path if `DirectoryPath` can not be created or written to.
|
||||
''' </summary>
|
||||
''' <param name="DirectoryPath">The directory to create</param>
|
||||
''' <param name="TestWriteAccess">Should a write access test be performed?</param>
|
||||
''' <returns>The used path</returns>
|
||||
Public Function CreateDirectory(DirectoryPath As String, Optional TestWriteAccess As Boolean = True) As String
|
||||
Dim oFinalPath As String
|
||||
If Directory.Exists(DirectoryPath) Then
|
||||
_logger.Debug("Directory {0} already exists. Skipping.", DirectoryPath)
|
||||
oFinalPath = DirectoryPath
|
||||
Else
|
||||
Try
|
||||
Directory.CreateDirectory(DirectoryPath)
|
||||
oFinalPath = DirectoryPath
|
||||
Catch ex As Exception
|
||||
_logger.Error(ex)
|
||||
_logger.Warn("Directory {0} could not be created. Temp path will be used instead.", DirectoryPath)
|
||||
oFinalPath = Path.GetTempPath()
|
||||
End Try
|
||||
End If
|
||||
|
||||
If TestWriteAccess AndAlso Not TestPathIsWritable(DirectoryPath) Then
|
||||
_logger.Warn("Directory {0} is not writable. Temp path will be used instead.", DirectoryPath)
|
||||
oFinalPath = Path.GetTempPath()
|
||||
Else
|
||||
oFinalPath = DirectoryPath
|
||||
End If
|
||||
|
||||
_logger.Debug("Using path {0}", oFinalPath)
|
||||
|
||||
Return oFinalPath
|
||||
End Function
|
||||
|
||||
Public Function TestPathIsWritable(DirectoryPath As String) As Boolean
|
||||
Try
|
||||
Dim fileAccessPath = Path.Combine(DirectoryPath, FILE_NAME_ACCESS_TEST)
|
||||
Using fs As FileStream = IO.File.Create(fileAccessPath)
|
||||
fs.WriteByte(0)
|
||||
End Using
|
||||
|
||||
IO.File.Delete(fileAccessPath)
|
||||
Return True
|
||||
Catch ex As Exception
|
||||
Return False
|
||||
End Try
|
||||
End Function
|
||||
|
||||
Public Function TestPathIsDirectory(Path As String) As Boolean
|
||||
If Not Directory.Exists(Path) Then
|
||||
Return False
|
||||
End If
|
||||
|
||||
Dim oIsDirectory As Boolean = (System.IO.File.GetAttributes(Path) And FileAttributes.Directory) = FileAttributes.Directory
|
||||
Return oIsDirectory
|
||||
End Function
|
||||
|
||||
End Class
|
||||
455
WinLineArtikelnummerGenerator/Modules/LogConfig.vb
Normal file
455
WinLineArtikelnummerGenerator/Modules/LogConfig.vb
Normal file
@@ -0,0 +1,455 @@
|
||||
Imports System.IO
|
||||
Imports System.Reflection
|
||||
Imports NLog
|
||||
Imports NLog.Config
|
||||
Imports NLog.Targets
|
||||
|
||||
''' <module>LogConfig</module>
|
||||
''' <version>0.0.1.0</version>
|
||||
''' <date>02.10.2018</date>
|
||||
''' <summary>
|
||||
''' Module that writes file-logs to different locations:
|
||||
''' local application data, the current directory or a custom path.
|
||||
''' Files and directories will be automatically created.
|
||||
''' </summary>
|
||||
''' <dependencies>
|
||||
''' NLog, >= 4.5.8
|
||||
''' </dependencies>
|
||||
''' <example>
|
||||
''' Imports DigitalData.Modules.Logging
|
||||
'''
|
||||
''' Class FooProgram
|
||||
''' Private Logger as Logger
|
||||
''' Private LogConfig as LogConfig
|
||||
'''
|
||||
''' Public Sub New()
|
||||
''' LogConfig = new LogConfig(args)
|
||||
''' Logger = LogConfig.GetLogger()
|
||||
''' End Sub
|
||||
'''
|
||||
''' Public Sub Bar()
|
||||
''' Logger.Info("Baz")
|
||||
''' End Sub
|
||||
''' End Class
|
||||
'''
|
||||
''' Class FooLib
|
||||
''' Private Logger as NLog.Logger
|
||||
'''
|
||||
''' Public Sub New(LogConfig as LogConfig)
|
||||
''' Logger = LogConfig.GetLogger()
|
||||
''' End Sub
|
||||
'''
|
||||
''' Public Sub Bar()
|
||||
''' Logger.Info("Baz")
|
||||
''' End Sub
|
||||
''' End Class
|
||||
''' </example>
|
||||
''' <remarks>
|
||||
''' If logpath can not be written to, falls back to temp folder as defined in:
|
||||
''' https://docs.microsoft.com/de-de/dotnet/api/system.io.path.gettemppath?view=netframework-4.7.2
|
||||
'''
|
||||
''' If used in a service, LogPath must be set to CustomPath, otherwise the Log will be written to System32!
|
||||
'''
|
||||
''' For NLog Troubleshooting, set the following Environment variables to write the NLog internal Log:
|
||||
''' - NLOG_INTERNAL_LOG_LEVEL: Debug
|
||||
''' - NLOG_INTERNAL_LOG_FILE: ex. C:\Temp\Nlog_Internal.log
|
||||
''' </remarks>
|
||||
Public Class LogConfig
|
||||
#Region "Private Properties"
|
||||
Private Const OPEN_FILE_CACHE_TIMEOUT As Integer = 5
|
||||
Private Const OPEN_FILE_FLUSH_TIMEOUT As Integer = 5
|
||||
Private Const AUTO_FLUSH As Boolean = True
|
||||
|
||||
Private Const KEEP_FILES_OPEN As Boolean = False
|
||||
Private Const KEEP_FILES_OPEN_DEBUG As Boolean = True
|
||||
|
||||
' MAX_ARCHIVES_FILES works like this (in version 4.5.8):
|
||||
' 0 = keep ALL archives files
|
||||
' 1 = only keep latest logfile and NO archive files
|
||||
' n = keep n archive files
|
||||
Private Const MAX_ARCHIVE_FILES_DEFAULT As Integer = 0
|
||||
Private Const MAX_ARCHIVE_FILES_DEBUG_DETAIL As Integer = 0
|
||||
Private Const ARCHIVE_EVERY As FileArchivePeriod = FileArchivePeriod.Day
|
||||
|
||||
Private Const FILE_NAME_FORMAT_DEFAULT As String = "${shortdate}-${var:product}${var:suffix}.log"
|
||||
Private Const FILE_NAME_FORMAT_DEBUG As String = "${shortdate}-${var:product}${var:suffix}-Debug.log"
|
||||
Private Const FILE_NAME_FORMAT_ERROR As String = "${shortdate}-${var:product}${var:suffix}-Error.log"
|
||||
|
||||
Private Const TARGET_DEFAULT As String = "defaultTarget"
|
||||
Private Const TARGET_ERROR_EX As String = "errorExceptionTarget"
|
||||
Private Const TARGET_ERROR As String = "errorTarget"
|
||||
Private Const TARGET_DEBUG As String = "debugTarget"
|
||||
Private Const TARGET_MEMORY As String = "memoryTarget"
|
||||
|
||||
Private Const DATE_FORMAT_LONG As String = "${longdate}"
|
||||
Private Const DATE_FORMAT_DEFAULT As String = "${date:format=yyyy-MM-dd HH\:mm\:ss}"
|
||||
|
||||
Private Const LOG_FORMAT_BASE As String = DATE_FORMAT_DEFAULT & "|${logger:shortName=True}|${level:uppercase=true}"
|
||||
Private Const LOG_FORMAT_BASE_LONG_DATE As String = DATE_FORMAT_LONG & "|${logger:shortName=True}|${level:uppercase=true}"
|
||||
Private Const LOG_FORMAT_CALLSITE As String = "${callsite:className=false:fileName=true:includeSourcePath=false:methodName=true}"
|
||||
|
||||
Private Const LOG_FORMAT_DEFAULT As String = LOG_FORMAT_BASE & " >> ${message}"
|
||||
Private Const LOG_FORMAT_EXCEPTION As String = LOG_FORMAT_BASE & " >> ${exception:format=Message}${newline}${exception:format=StackTrace}"
|
||||
Private Const LOG_FORMAT_DEBUG As String = LOG_FORMAT_BASE_LONG_DATE & " >> " & LOG_FORMAT_CALLSITE & " -> ${message}"
|
||||
Private Const LOG_FORMAT_MEMORY As String = LOG_FORMAT_BASE_LONG_DATE & " >> ${message}${newline}${exception:format=Message}${newline}${exception:format=StackTrace}"
|
||||
|
||||
Private Const FILE_NAME_ACCESS_TEST = "accessTest.txt"
|
||||
Private Const FOLDER_NAME_LOG = "Log"
|
||||
|
||||
Private ReadOnly failSafePath As String = Path.GetTempPath()
|
||||
Private ReadOnly basePath As String = failSafePath
|
||||
|
||||
Private config As LoggingConfiguration
|
||||
Private isDebug As Boolean = False
|
||||
#End Region
|
||||
#Region "Public Properties"
|
||||
Public Enum PathType As Integer
|
||||
AppData = 0
|
||||
CurrentDirectory = 1
|
||||
CustomPath = 2
|
||||
Temp = 3
|
||||
End Enum
|
||||
|
||||
''' <summary>
|
||||
''' Returns the NLog.LogFactory object that is used to create Loggers
|
||||
''' </summary>
|
||||
''' <returns>LogFactory object</returns>
|
||||
Public ReadOnly Property LogFactory As LogFactory
|
||||
|
||||
''' <summary>
|
||||
''' Returns the path to the current default logfile
|
||||
''' </summary>
|
||||
''' <returns>Filepath to the logfile</returns>
|
||||
Public ReadOnly Property LogFile As String
|
||||
|
||||
''' <summary>
|
||||
''' Returns the path to the current log directory
|
||||
''' </summary>
|
||||
''' <returns>Directory path to the log directory</returns>
|
||||
Public ReadOnly Property LogDirectory As String
|
||||
|
||||
''' <summary>
|
||||
''' Determines if a debug log will be written
|
||||
''' </summary>
|
||||
''' <returns>True, if debug log will be written. False otherwise.</returns>
|
||||
Public Property Debug As Boolean
|
||||
Get
|
||||
Return isDebug
|
||||
End Get
|
||||
Set(isDebug As Boolean)
|
||||
Me.isDebug = isDebug
|
||||
'GetLogger().Debug("=> Debug is now {0}", isDebug)
|
||||
ReloadConfig(isDebug)
|
||||
End Set
|
||||
End Property
|
||||
|
||||
''' <summary>
|
||||
''' Returns Logs in Memory as List(Of String) if Debug is enabled
|
||||
''' Returns an empty list if debug is disabled
|
||||
''' </summary>
|
||||
''' <returns>A list of log messages</returns>
|
||||
Public ReadOnly Property Logs As List(Of String)
|
||||
Get
|
||||
Dim oTarget = config.FindTargetByName(Of MemoryTarget)(TARGET_MEMORY)
|
||||
Return oTarget?.Logs.ToList()
|
||||
End Get
|
||||
End Property
|
||||
|
||||
Public ReadOnly Property NLogConfig As LoggingConfiguration
|
||||
Get
|
||||
Return config
|
||||
End Get
|
||||
End Property
|
||||
|
||||
#End Region
|
||||
|
||||
''' <summary>
|
||||
''' Initializes a new LogConfig object with a logpath and optinally a filename-suffix.
|
||||
''' </summary>
|
||||
''' <param name="LogPath">The basepath to write logs to. Can be AppData, CurrentDirectory or CustomPath.</param>
|
||||
''' <param name="CustomLogPath">If `logPath` is set to custom, this defines the custom logPath.</param>
|
||||
''' <param name="Suffix">If set to anything other than Nothing, extends the logfile name with this suffix.</param>
|
||||
''' <param name="CompanyName">CompanyName is used to construct log-path in when LogPath is set to PathType:AppData</param>
|
||||
''' <param name="ProductName">ProductName is used to construct log-path in when LogPath is set to PathType:AppData</param>
|
||||
Public Sub New(LogPath As PathType,
|
||||
Optional CustomLogPath As String = Nothing,
|
||||
Optional Suffix As String = Nothing,
|
||||
Optional CompanyName As String = Nothing,
|
||||
Optional ProductName As String = Nothing)
|
||||
|
||||
If LogPath = PathType.AppData And (ProductName Is Nothing Or CompanyName Is Nothing) Then
|
||||
Throw New ArgumentException("Modules.Logging: PathType is AppData and either CompanyName or ProductName was not supplied!")
|
||||
End If
|
||||
|
||||
If LogPath = PathType.CurrentDirectory Then
|
||||
Throw New ArgumentException("Modules.Logging: LogPath.CurrentDirectory is deprecated. Please use LogPath.CustomPath!")
|
||||
End If
|
||||
|
||||
If LogPath = PathType.AppData Then
|
||||
Dim appDataDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
|
||||
basePath = Path.Combine(appDataDir, CompanyName, ProductName, FOLDER_NAME_LOG)
|
||||
ElseIf LogPath = PathType.Temp Then
|
||||
basePath = failSafePath
|
||||
Else 'Custom Path
|
||||
basePath = CustomLogPath
|
||||
End If
|
||||
|
||||
' If directory does not exist, try to create it!
|
||||
If Not Directory.Exists(basePath) Then
|
||||
Try
|
||||
Directory.CreateDirectory(basePath)
|
||||
Catch ex As Exception
|
||||
' If creation fails, use failSafe path
|
||||
basePath = failSafePath
|
||||
End Try
|
||||
End If
|
||||
|
||||
' Try to create a file in `basePath` to check write permissions
|
||||
Try
|
||||
Dim fileAccessPath = Path.Combine(basePath, FILE_NAME_ACCESS_TEST)
|
||||
Using fs As FileStream = System.IO.File.Create(fileAccessPath)
|
||||
fs.WriteByte(0)
|
||||
End Using
|
||||
|
||||
IO.File.Delete(fileAccessPath)
|
||||
Catch ex As Exception
|
||||
' If creation fails, use failSafe path
|
||||
basePath = failSafePath
|
||||
End Try
|
||||
|
||||
' Set the suffix to the given string if it exists
|
||||
Dim logFileSuffix As String = String.Empty
|
||||
|
||||
If Suffix IsNot Nothing AndAlso Suffix.Count > 0 Then
|
||||
logFileSuffix = $"-{Suffix}"
|
||||
End If
|
||||
|
||||
Dim oProductName As String = "Main"
|
||||
|
||||
If ProductName IsNot Nothing Then
|
||||
oProductName = ProductName
|
||||
End If
|
||||
|
||||
' Create config object and initalize it
|
||||
config = GetConfig(oProductName, logFileSuffix)
|
||||
|
||||
' Save config
|
||||
LogFactory = New LogFactory With {
|
||||
.Configuration = config
|
||||
}
|
||||
|
||||
' Save log paths for files/directory
|
||||
LogDirectory = basePath
|
||||
LogFile = GetCurrentLogFilePath()
|
||||
End Sub
|
||||
|
||||
Private Sub CheckMyApplication()
|
||||
Dim oAssembly = Assembly.GetEntryAssembly()
|
||||
Dim oMyApp = Nothing
|
||||
For Each oType As Type In oAssembly.DefinedTypes
|
||||
If oType.Name = "MyApplication" Then
|
||||
oMyApp = oType
|
||||
Exit For
|
||||
End If
|
||||
Next
|
||||
|
||||
oMyApp.GetType().GetProperty("")
|
||||
End Sub
|
||||
|
||||
''' <summary>
|
||||
''' Returns the Logger for the calling class
|
||||
''' </summary>
|
||||
''' <returns>An object of Logging.Logger</returns>
|
||||
<DebuggerStepThrough()>
|
||||
Public Function GetLogger() As Logger
|
||||
Dim oClassName As String = GetClassFullName()
|
||||
Return LogFactory.GetLogger(Of Logger)(oClassName)
|
||||
End Function
|
||||
|
||||
''' <summary>
|
||||
''' Returns the Logger for a class specified by `ClassName`
|
||||
''' </summary>
|
||||
''' <param name="ClassName">The name of the class the logger belongs to</param>
|
||||
''' <returns>An object of Logging.Logger</returns>
|
||||
<DebuggerStepThrough()>
|
||||
Public Function GetLogger(ClassName As String) As Logger
|
||||
Return LogFactory.GetLogger(Of Logger)(ClassName)
|
||||
End Function
|
||||
|
||||
''' <summary>
|
||||
''' Clears the internal log
|
||||
''' </summary>
|
||||
Public Sub ClearLogs()
|
||||
Dim oTarget = config.FindTargetByName(Of MemoryTarget)(TARGET_MEMORY)
|
||||
oTarget?.Logs.Clear()
|
||||
End Sub
|
||||
|
||||
''' <summary>
|
||||
''' Gets the fully qualified name of the class invoking the calling method,
|
||||
''' including the namespace but Not the assembly.
|
||||
''' </summary>
|
||||
''' <returns>The fully qualified class name</returns>
|
||||
''' <remarks>This method is very resource-intensive!</remarks>
|
||||
<DebuggerStepThrough()>
|
||||
Public Shared Function GetClassFullName() As String
|
||||
Dim oFramesToSkip As Integer = 2
|
||||
Dim oClassName As String = String.Empty
|
||||
Dim oStackTrace = Environment.StackTrace
|
||||
Dim oStackTraceLines = oStackTrace.Replace(vbCr, "").Split({vbLf}, StringSplitOptions.RemoveEmptyEntries)
|
||||
|
||||
For i As Integer = 0 To oStackTraceLines.Length - 1
|
||||
Dim oCallingClassAndMethod = oStackTraceLines(i).Split({" ", "<>", "(", ")"}, StringSplitOptions.RemoveEmptyEntries)(1)
|
||||
Dim oMethodStartIndex As Integer = oCallingClassAndMethod.LastIndexOf(".", StringComparison.Ordinal)
|
||||
|
||||
If oMethodStartIndex > 0 Then
|
||||
Dim oCallingClass = oCallingClassAndMethod.Substring(0, oMethodStartIndex)
|
||||
oClassName = oCallingClass.TrimEnd("."c)
|
||||
|
||||
If Not oClassName.StartsWith("System.Environment") AndAlso oFramesToSkip <> 0 Then
|
||||
i += oFramesToSkip - 1
|
||||
oFramesToSkip = 0
|
||||
Continue For
|
||||
End If
|
||||
|
||||
If Not oClassName.StartsWith("System.") Then Exit For
|
||||
End If
|
||||
Next
|
||||
|
||||
Return oClassName
|
||||
End Function
|
||||
|
||||
''' <summary>
|
||||
''' Returns the initial log configuration
|
||||
''' </summary>
|
||||
''' <param name="productName">The chosen productname</param>
|
||||
''' <param name="logFileSuffix">The chosen suffix</param>
|
||||
''' <returns>A NLog.LoggingConfiguration object</returns>
|
||||
Private Function GetConfig(productName As String, logFileSuffix As String) As LoggingConfiguration
|
||||
config = New LoggingConfiguration()
|
||||
config.Variables("product") = productName
|
||||
config.Variables("suffix") = logFileSuffix
|
||||
|
||||
' Add default targets
|
||||
config.AddTarget(TARGET_ERROR_EX, GetErrorExceptionLogTarget(basePath))
|
||||
config.AddTarget(TARGET_ERROR, GetErrorLogTarget(basePath))
|
||||
config.AddTarget(TARGET_DEFAULT, GetDefaultLogTarget(basePath))
|
||||
config.AddTarget(TARGET_DEBUG, GetDebugLogTarget(basePath))
|
||||
config.AddTarget(TARGET_MEMORY, GetMemoryDebugTarget())
|
||||
|
||||
' Add default rules
|
||||
AddDefaultRules(config)
|
||||
|
||||
Return config
|
||||
End Function
|
||||
|
||||
''' <summary>
|
||||
''' Adds the default rules
|
||||
''' </summary>
|
||||
''' <param name="config">A NLog.LoggingConfiguration object</param>
|
||||
Private Sub AddDefaultRules(ByRef config As LoggingConfiguration)
|
||||
config.AddRuleForOneLevel(LogLevel.Error, TARGET_ERROR_EX)
|
||||
config.AddRuleForOneLevel(LogLevel.Fatal, TARGET_ERROR_EX)
|
||||
config.AddRuleForOneLevel(LogLevel.Warn, TARGET_ERROR)
|
||||
config.AddRuleForOneLevel(LogLevel.Warn, TARGET_DEFAULT)
|
||||
config.AddRuleForOneLevel(LogLevel.Info, TARGET_DEFAULT)
|
||||
End Sub
|
||||
|
||||
''' <summary>
|
||||
''' Returns the full path of the current default log file.
|
||||
''' </summary>
|
||||
''' <returns>Full path of the current default log file</returns>
|
||||
Private Function GetCurrentLogFilePath()
|
||||
Dim logEventInfo As New LogEventInfo() With {.TimeStamp = Date.Now}
|
||||
Dim target As FileTarget = config.FindTargetByName(TARGET_DEFAULT)
|
||||
Dim fileName As String = target.FileName.Render(logEventInfo)
|
||||
|
||||
Return fileName
|
||||
End Function
|
||||
|
||||
''' <summary>
|
||||
''' Reconfigures and re-adds all loggers, optionally adding the debug rule.
|
||||
''' </summary>
|
||||
''' <param name="Debug">Adds the Debug rule if true.</param>
|
||||
Private Sub ReloadConfig(Optional Debug As Boolean = False)
|
||||
' Clear Logging Rules
|
||||
config.LoggingRules.Clear()
|
||||
|
||||
' Add default rules
|
||||
AddDefaultRules(config)
|
||||
|
||||
' Add debug rule, if configured
|
||||
If Debug Then
|
||||
config.AddRuleForOneLevel(LogLevel.Debug, TARGET_DEBUG)
|
||||
config.AddRuleForAllLevels(TARGET_MEMORY)
|
||||
End If
|
||||
|
||||
' Reload all running loggers
|
||||
LogFactory.ReconfigExistingLoggers()
|
||||
End Sub
|
||||
|
||||
#Region "Log Targets"
|
||||
Private Function GetDefaultLogTarget(basePath As String) As FileTarget
|
||||
Dim defaultLog As New FileTarget() With {
|
||||
.FileName = Path.Combine(basePath, FILE_NAME_FORMAT_DEFAULT),
|
||||
.Name = TARGET_DEFAULT,
|
||||
.Layout = LOG_FORMAT_DEFAULT,
|
||||
.MaxArchiveFiles = MAX_ARCHIVE_FILES_DEFAULT,
|
||||
.ArchiveEvery = ARCHIVE_EVERY,
|
||||
.KeepFileOpen = KEEP_FILES_OPEN
|
||||
}
|
||||
|
||||
Return defaultLog
|
||||
End Function
|
||||
Private Function GetErrorExceptionLogTarget(basePath As String) As FileTarget
|
||||
Dim errorLogWithExceptions As New FileTarget() With {
|
||||
.FileName = Path.Combine(basePath, FILE_NAME_FORMAT_ERROR),
|
||||
.Name = TARGET_ERROR_EX,
|
||||
.Layout = LOG_FORMAT_EXCEPTION,
|
||||
.MaxArchiveFiles = MAX_ARCHIVE_FILES_DEFAULT,
|
||||
.ArchiveEvery = ARCHIVE_EVERY,
|
||||
.KeepFileOpen = KEEP_FILES_OPEN
|
||||
}
|
||||
|
||||
Return errorLogWithExceptions
|
||||
End Function
|
||||
|
||||
Private Function GetErrorLogTarget(basePath As String) As FileTarget
|
||||
Dim errorLog As New FileTarget() With {
|
||||
.FileName = Path.Combine(basePath, FILE_NAME_FORMAT_ERROR),
|
||||
.Name = TARGET_ERROR,
|
||||
.Layout = LOG_FORMAT_DEFAULT,
|
||||
.MaxArchiveFiles = MAX_ARCHIVE_FILES_DEFAULT,
|
||||
.ArchiveEvery = ARCHIVE_EVERY,
|
||||
.KeepFileOpen = KEEP_FILES_OPEN
|
||||
}
|
||||
|
||||
Return errorLog
|
||||
End Function
|
||||
|
||||
Private Function GetDebugLogTarget(basePath As String) As FileTarget
|
||||
Dim debugLog As New FileTarget() With {
|
||||
.FileName = Path.Combine(basePath, FILE_NAME_FORMAT_DEBUG),
|
||||
.Name = TARGET_DEBUG,
|
||||
.Layout = LOG_FORMAT_DEBUG,
|
||||
.MaxArchiveFiles = MAX_ARCHIVE_FILES_DEBUG_DETAIL,
|
||||
.ArchiveEvery = ARCHIVE_EVERY,
|
||||
.KeepFileOpen = KEEP_FILES_OPEN_DEBUG,
|
||||
.OpenFileCacheTimeout = OPEN_FILE_CACHE_TIMEOUT,
|
||||
.AutoFlush = AUTO_FLUSH,
|
||||
.OpenFileFlushTimeout = OPEN_FILE_FLUSH_TIMEOUT
|
||||
}
|
||||
|
||||
Return debugLog
|
||||
End Function
|
||||
|
||||
Private Function GetMemoryDebugTarget() As MemoryTarget
|
||||
Dim memoryLog As New MemoryTarget() With {
|
||||
.Layout = LOG_FORMAT_MEMORY,
|
||||
.Name = TARGET_MEMORY,
|
||||
.OptimizeBufferReuse = True
|
||||
}
|
||||
|
||||
Return memoryLog
|
||||
End Function
|
||||
#End Region
|
||||
End Class
|
||||
28
WinLineArtikelnummerGenerator/Modules/Logger.vb
Normal file
28
WinLineArtikelnummerGenerator/Modules/Logger.vb
Normal file
@@ -0,0 +1,28 @@
|
||||
Imports NLog
|
||||
|
||||
Public Class Logger
|
||||
Inherits NLog.Logger
|
||||
Implements ILogger
|
||||
|
||||
''' <summary>
|
||||
''' Prints a preformatted Block including a block identifier
|
||||
''' </summary>
|
||||
''' <param name="blockId">A unique Identifier for this block, eg. DocId, FullPath, ..</param>
|
||||
<DebuggerStepThrough()>
|
||||
Public Sub NewBlock(blockId As String)
|
||||
Dim message As String = $"-----> Start of Block {blockId}"
|
||||
Dim logEventInfo As New LogEventInfo(LogLevel.Info, Name, message)
|
||||
Dim WrapperType As Type = GetType(Logger)
|
||||
|
||||
Log(WrapperType, logEventInfo)
|
||||
End Sub
|
||||
|
||||
<DebuggerStepThrough()>
|
||||
Public Sub EndBlock()
|
||||
Dim message As String = $"<----- End of Block"
|
||||
Dim logEventInfo As New LogEventInfo(LogLevel.Info, Name, message)
|
||||
Dim WrapperType As Type = GetType(Logger)
|
||||
|
||||
Log(WrapperType, logEventInfo)
|
||||
End Sub
|
||||
End Class
|
||||
Reference in New Issue
Block a user