Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton logger, static logger, factory logger... how to log?

Tags:

c#

logging

I am wrapping the patterns & practices Enterprise Library Logging Application Block for an application written in .NET.

I want to be able to subclass a logger (i.e to provide domain specific logging).

What is the best way to do this?

For e.g, I have a static Logger class at the moment, but this does not allow me to specialize it for domain specific logging.

For example,

Log(MyDomainObj obj, string msg)

like image 892
geejay Avatar asked Aug 03 '09 12:08

geejay


People also ask

How is singleton used for logging?

It is used where only a single instance of a class is required to control the action throughout the execution. A singleton class shouldn't have multiple instances in any case and at any cost. Singleton classes are used for logging, driver objects, caching and thread pool, database connections.

Should logger be singleton or scoped?

A logger is, perhaps, the most iconic example of a singleton use case. You need to manage access to a resource (file), you only want one to exist, and you'll need to use it in a lot of places.

Is Python singleton logger?

The Logger class performs the logging and inherits the singleton behaviour from the Singleton class. This class inherits the same singleton behaviour as Logger because it also derives from the Singleton class. This code creates a single Logger object and a single Database object.


2 Answers

You could even do better than that. Write a wrapper class that wraps either Nlog or log4net or whatnot. You can then use that wrapper class (maybe use an interface to it if you really want to decouple things) in your code. This way, if you decide to change logger class, you need to change just one class and not edit all your classes.

like image 145
Sardathrion - against SE abuse Avatar answered Oct 14 '22 06:10

Sardathrion - against SE abuse


Check out NLog. They use this sort of pattern:

private static Logger myDomainLogger = LogManager.GetCurrentClassLogger();

You can then specialize the output based on the class that myDomainLogger belongs to.

More detail:

class MyDomain
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    private void SomeFunc()
    {
        _logger.Trace("this is a test");
    }
}

Then in your output you can have it output "MyDomain.SomeFunc" as part of the "this is a test" message.

like image 28
Gabe Avatar answered Oct 14 '22 08:10

Gabe