0

I'm writing a program and writing my own logging at the moment but I would like to start using a library. Does the common logging library in C# allow for 1 logger that is shared globally? I have multiple classes and I would like them all to log into 1 file without passing some reference of the logger into each class. Also would this be good practice if possible?

class myclass1{

    //declare logger here...

    funca() {
        log("run status");

        myclass2 mc = new myclass();
        mc.funcb();
    }
}

another file.

class myclass2{

    funcb() {
        //don't need to pass logger reference just log here.
        log("run status");
    }
}
Lightsout
  • 3,454
  • 2
  • 36
  • 65

2 Answers2

-1

You can use NLog. All details are in the link. If you are using asp.net core, you can use Microsoft.Extensions.Logging.

Here is the SO for comparison between Nlog and Microsoft.Extensions.Logging.

cdev
  • 5,043
  • 2
  • 33
  • 32
-2

Ended up going with Serilog, simple syntax and didn't have to redeclare logger in new class.

class myclass1{

    Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.Console()
                .WriteTo.File("logs/myapp.txt", rollingInterval: RollingInterval.Day)
                .CreateLogger();

    

    funca() {
        Log.Information("Hello, world!");

        myclass2 mc = new myclass();
        mc.funcb();
    }
}

another file

class myclass2{

    funcb() {
        //don't need to pass logger reference just log here.
        Log.Information("Initialized test class!");
    }
}
Lightsout
  • 3,454
  • 2
  • 36
  • 65