Using iLogger in WinForms with VB.Net

Darren Rose 311 Reputation points
2020-12-28T17:45:31.367+00:00

Hi

Can someone please give me some guidance on implementing iLogger using VB.Net in a WinForms application?

Most documentation seems to cover C# and converting the code doesn't seem to work so not sure where I am going wrong.

Spent a while with Mr Google and trying various suggestions but nearly everything I read was C# and not using WinForms.

Reason for interest is that everyting I read seems to suggest iLogger is the future etc so wanted to learn how to use it, so any comments on this or better options etc would be useful to hear your opinions

Developer technologies | VB

Answer accepted by question author

Karen Payne MVP 35,606 Reputation points Volunteer Moderator
2020-12-28T20:31:58.873+00:00

Hello @Darren Rose

The following are code snippets from this class project in this repository on GitHub converted from this C# cide in this repository on GitHub.

Notes

  • There is more code than simply shown here
  • The conversion was not straightforward as I used C# 9 features that have no equivalent in VB which took a tad longer than expected.

Hopefully this is of use to you and note what you were looking at is for use with web apps.

.NET Core version

https://github.com/karenpayneoregon/csharp-features/tree/master/ConsoleApp_vb

Program.vb

Imports Microsoft.Extensions.DependencyInjection  
Imports Microsoft.Extensions.Logging  
  
Module Program  
    Sub Main(args As String())  
  
        Dim serviceCollection As New ServiceCollection()  
        ConfigureServices(serviceCollection)  
  
        Dim serviceProvider = serviceCollection.BuildServiceProvider()  
  
        Dim someClass = serviceProvider.GetService(Of SomeClass)()  
  
        someClass.LogInfo("Hello")  
  
    End Sub  
    Private Sub ConfigureServices(ByVal services As IServiceCollection)  
  
        services.AddLogging(Function(configure) configure.AddConsole()).AddTransient(Of SomeClass)()  
  
    End Sub  
  
End Module  

Supporting class

Imports Microsoft.Extensions.Logging  
Public Class SomeClass  
    Private ReadOnly _logger As ILogger(Of SomeClass)  
  
    Private Sub New(logger As ILogger(Of SomeClass))  
        _logger = logger  
    End Sub  
  
    Private Sub LogCritical(message As String)  
        _logger.Log(LogLevel.Critical, message)  
        _logger.LogInformation("")  
    End Sub  
    Public Sub LogInfo(message As String)  
        _logger.LogInformation(message)  
    End Sub  
End Class  

Enum

Public Enum LogLevel  
    Warning  
    Errors  
    General  
End Enum  

Interface

Public Interface ILogger  
    Property FileName() As String  
    Sub LogWarning(message As String)  
    Sub LogError(message As String)  
    Sub LogGeneral(message As String)  
    Sub Log(ByVal level As LogLevel, ByVal message As String)  
End Interface  

Write to a file

Public Class LogManager  
    Implements ILogger  

    Public Property FileName() As String Implements ILogger.FileName  
  
    Public Sub LogWarning(message As String) Implements ILogger.LogWarning  
        Log(LogLevel.Warning, message)  
    End Sub  
  
    Public Sub LogError(message As String) Implements ILogger.LogError  
        Log(LogLevel.Errors, message)  
    End Sub  
  
    Public Sub LogGeneral(message As String) Implements ILogger.LogGeneral  
        Log(LogLevel.General, message)  
    End Sub  
  
    Public Sub Log(ByVal level As LogLevel, ByVal message As String) Implements ILogger.Log  
        If String.IsNullOrWhiteSpace(FileName) Then  
            FileName = "ApplicationLog.csv"  
        End If  
  
        Try  
            If File.Exists(FileName) Then  
                Dim contents = File.ReadAllLines(FileName).ToList()  
                contents.Add($"{DateTime.Now},{level},{message}")  
                File.WriteAllLines(FileName, contents.ToArray())  
            Else  
                File.WriteAllText(FileName, $"{DateTime.Now},{level},{message}")  
            End If  
        Catch e As Exception  
            Exceptions.Write(e)  
        End Try  
    End Sub  
End Class  

Write to the console

Public Class ConsoleLogger  
    Implements ILogger  
    Public Property FileName As String Implements ILogger.FileName  
  
    Public Sub LogWarning(message As String) Implements ILogger.LogWarning  
        Log(LogLevel.Warning, message)  
    End Sub  
  
    Public Sub LogError(message As String) Implements ILogger.LogError  
        Log(LogLevel.Errors, message)  
    End Sub  
  
    Public Sub LogGeneral(message As String) Implements ILogger.LogGeneral  
        Log(LogLevel.General, message)  
    End Sub  
  
    Public Sub Log(level As LogLevel, message As String) Implements ILogger.Log  
        Console.WriteLine($"{level}, {message}")  
    End Sub  
End Class  

AddLogging is not a member of IServiceCollection

Make sure you have the NuGet package Microsoft.Extensions.DependencyInjection installed and the others I've listed below which is accessed by double clicking the project file in VS2019 or if a lower version of VS, upload the project and edit the project file.

<Project Sdk="Microsoft.NET.Sdk">  
  
  <PropertyGroup>  
    <OutputType>WinExe</OutputType>  
    <TargetFramework>net5.0-windows</TargetFramework>  
    <RootNamespace>WinFormsAppILogger</RootNamespace>  
    <StartupObject>Sub Main</StartupObject>  
    <UseWindowsForms>true</UseWindowsForms>  
    <MyType>WindowsForms</MyType>  
  </PropertyGroup>  
  
  <ItemGroup>  
    <Import Include="System.Data" />  
    <Import Include="System.Drawing" />  
    <Import Include="System.Windows.Forms" />  
  </ItemGroup>  
  
  <ItemGroup>  
    <PackageReference Include="Microsoft.Extensions.Configuration" Version="5.0.0" />  
    <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="5.0.0" />  
    <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="5.0.0" />  
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="5.0.0" />  
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="5.0.1" />  
    <PackageReference Include="Microsoft.Extensions.Logging" Version="5.0.0" />  
    <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="5.0.0" />  
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="5.0.0" />  
  </ItemGroup>  
  
  <ItemGroup>  
    <Compile Update="My Project\Application.Designer.vb">  
      <DesignTime>True</DesignTime>  
      <AutoGen>True</AutoGen>  
      <DependentUpon>Application.myapp</DependentUpon>  
    </Compile>  
  </ItemGroup>  
  
  <ItemGroup>  
    <None Update="appsettings.json">  
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>  
    </None>  
    <None Update="My Project\Application.myapp">  
      <Generator>MyApplicationCodeGenerator</Generator>  
      <LastGenOutput>Application.Designer.vb</LastGenOutput>  
    </None>  
  </ItemGroup>  
  
</Project>  

52593-1111.png

52672-2222.png

Was this answer helpful?


1 additional answer

Sort by: Most helpful
  1. Anonymous
    2020-12-28T18:21:51.703+00:00

    Hi Can't help directly with the iLogger, but, are you aware of the lanfuage 'switch' at the top of the docs page(s)? ![51684-1.png][1] [1]: /api/attachments/51684-1.png?platform=QnA

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.