13

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));?

Q-bertsuit
  • 3,223
  • 6
  • 30
  • 55
  • 1
    Serilog isn't log4net. Why do you want to create a new logger for each class? To emit the class name? Check [Serilog add class name and method to log](https://stackoverflow.com/questions/47576733/c-sharp-asp-net-core-serilog-add-class-name-and-method-to-log) – Panagiotis Kanavos Jan 08 '21 at 11:40
  • 1
    You can also [use the `ForContext` or `ForContext` method](https://nblumhardt.com/2016/08/context-and-correlation-structured-logging-concepts-in-net-5/) to add context properties. You could use eg `Log.ForContext` or `Log.ForContext` – Panagiotis Kanavos Jan 08 '21 at 11:52
  • I have to either swap out the static log4net loggers in each class, or introduce DI and add the logger to all the constructors. I wan't to go the easiest route possible – Q-bertsuit Jan 08 '21 at 11:57
  • Thanks for the link, but in that example they are using DI and passing the logger in through the constructor. My task will be a lot simpler if I don't have to introduce a DI framework – Q-bertsuit Jan 08 '21 at 11:58
  • Seems like this is a duplicate https://stackoverflow.com/questions/51191454/log4net-method-getlogger-equivalent-in-serilog – Q-bertsuit Jan 08 '21 at 12:05
  • 2
    No, that answer is wrong, because it compares apples to juicers. Creating a new logger each time is *not* an end in itself. It's the way you include context information. None of the examples requires DI. They use DI simply because most applications use DI. There's no need to use dependency injection with Serilog. If you want to include context information, you can start directly with `FromContext` and get the same behavior as log4net. – Panagiotis Kanavos Jan 08 '21 at 12:12
  • 1
    I'd bet the DI middleware actually calls `FromContext` as well – Panagiotis Kanavos Jan 08 '21 at 12:13
  • I finally got it! Took me a while to understand what you meant about using ForContext. Thanks a bunch! Would you like to post it as a separate answer? – Q-bertsuit Jan 08 '21 at 13:06

1 Answers1

23

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

C. Augusto Proiete
  • 24,684
  • 2
  • 63
  • 91