András Tóth‘s professional blog
banditoth.net

Hey there 👋, I’m banditoth a .NET MAUI developer from Hungary.
I write about software development with .NET technologies.

You can find me on:
LinkedIn | Github | StackOverflow | X / Twitter | Threads

Tag: logging

  • Xamarin Forms: Logging with anything from Console to SQLite

    This content has 4 years. Some of the information in this post may be out of date or no longer work. Please, read this page keeping its age in your mind.

    And it’s also logging the invoked method name, and the file name containing the method!

    My Forms.RecurrenceToolkit NuGet package pack is now extended with logging functionality.

    You can use the pre-written Console and SQLite logger without writing much code, or you can implement your own logger in a few lines, and use it instantly simultaneous with other loggers.

    Install banditoth.Forms.RecurrenceToolkit.Logging.* packages, and enjoy the painless logging, and focus on the great ideas instead of being a copy paste robot. 🙂

    Usage

    In your App.xaml.cs, initalize the logger like:

    LoggingProvider.Initalize(
    	// If you have installed the console logger:
    	new ConsoleLogger(),
    	// If you have installed SQLite Logger:
    	new SQLiteLogger()
    	);
    

    The logger is including the calling method’s name, and the .cs file name in the logs. You can access the logger from anywhere by calling these methods:

    LoggingProvider.LogCritical("It's a critical message");
    LoggingProvider.LogDebug("It's a debug message");
    LoggingProvider.LogError("It's an error message");
    LoggingProvider.LogException(new Exception(), "It's an exception");
    LoggingProvider.LogInformation("It's an information message");
    LoggingProvider.LogTrace("It's a trace message");
    LoggingProvider.LogTrace(new StackTrace());
    LoggingProvider.LogWarning("It's a warning message");
    

    By default, the console and the SQLite logger logs exceptions in error level.

    You can implement your own logger by deriving from BaseLogger class, like:

    public class CustomLogger : BaseLogger
    	{
    		public CustomLogger() : base(new LoggerOptions()
    		{
    			IncludeCallerSourceFullFileName = true, // This will print C:/Users/Path/AssemblyFile.cs
    			IncludeCallerSourceShortFileName = false, // This will print AssemblyFile.cs
    			ExceptionLevel = Enumerations.LogLevel.Error, // The LogExceptions calls routed to log to the loglevel set.
    			IncludeCallerMethodName = true // This can print the calling method's name
    		})
    		{
    
    		}
    		
    		public override void LogCritical(string criticalMessage, string callerMethod, string filePath)
    		{
    			// Your own method
    		}
    
    		// .. File continues
    

    Follow for more

    https://github.com/banditoth/Forms.RecurrenceToolkit

  • .NET Core : Logging with Log4NET in .NET Core application

    This content has 4 years. Some of the information in this post may be out of date or no longer work. Please, read this page keeping its age in your mind.

    There are tons of newly created logging engines for .NET Core. Log4Net is stable, old school technology in the market. Consider using newer logging technologies, such as NLog or Serilog. But if you want to use this engine, you can make it work.

    Start with the Microsoft’s tutorial, “Logging in .NET Core”. https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-5.0

    Install log4Net NuGet Package, and Microsoft.Extensions.Logging.Log4Net.AspNetCore package.

    Install-Package log4Net
    Install-Package Microsoft.Extensions.Logging.Log4Net.AspNetCore
    

    Make changes in your Program.cs file. In the CreateHostBuilder method, configure logging with the following code:

                    .ConfigureLogging((hostingContext, logging) =>
                    {
                        logging.AddConsole();
                        logging.AddLog4Net();
                    })
    

    If the “AddLog4Net” method call is unrecognized by IntelliSense, make sure you have installed the Logging extension NuGet package mentioned above.

    Add a new file to your project, and name it log4Net.config. The template should be used is Web Configuration file.

    Make changes in the newly generated file, here you can configure the applications logging. I’ve skipped Console logging, Microsoft’s console logger visualize logs much greater. You can learn configuring Log4Net more at https://logging.apache.org/log4net/release/manual/configuration.html
    A quick start configuration example:

    <?xml version="1.0" encoding="utf-8"?>
    <log4net>
    	<root>
    		<level value="ALL" />
    		<appender-ref ref="file" />
    	</root>
    	<appender name="file" type="log4net.Appender.RollingFileAppender">
    		<file value="myapp.log" />
    		<appendToFile value="true" />
    		<rollingStyle value="Size" />
    		<maxSizeRollBackups value="5" />
    		<maximumFileSize value="10MB" />
    		<staticLogFileName value="true" />
    		<layout type="log4net.Layout.PatternLayout">
    			<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
    		</layout>
    	</appender>
    </log4net>