Search code examples
c#.net-4.0serilog

Getting an instance of the Serilog logger without DI


I have a console app without dependency injection that uses log4net. I'm trying to replace log4net with Serilog.

This is close to how log4net is setup:

using log4net;
using log4net.Config;
using System;
using System.IO;
using System.Reflection;

namespace LoggingDemo.Log4Net
{
    class Program
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Program));
        static void Main(string[] args)
        {
            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
            log.Debug("Starting up");
            log.Debug("Shutting down");
            Console.ReadLine();
        }
    }
}

In other classes a logger is acquired by setting private static readonly ILog log = LogManager.GetLogger(typeof(Program));

Serilog is setup like this:

using Serilog;
using System;

namespace LoggingDemo.Serilog
{
    class Program
    {
        static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.Console()
                .WriteTo.File("logfile.log", rollingInterval: RollingInterval.Day)
                .CreateLogger();

            Log.Debug("Starting up");
            Log.Debug("Shutting down");

            Console.ReadLine();
        }
    }
}

How can I get an instance of the Serilog logger like we do with log4net in other classes, i.e private static readonly ILog log = LogManager.GetLogger(typeof(Program));?


Solution

  • Serilog allows events to be tagged with their source, generally speaking the name of the class writing them. You can do that using one of the ForContext methods of the Log class.

    In your examples above, it would something like this:

    private static readonly ILogger log = Log.ForContext<Program>();
    

    or

    private static readonly ILogger log = Log.ForContext(typeof(Program));
    

    The event written will include a property SourceContext with value "MyNamespace.MyClass" that can later be used to filter out noisy events, or selectively write them to particular sinks.


    Documentation: https://github.com/serilog/serilog/wiki/Writing-Log-Events#source-contexts