Singleton logger, static logger, factory logger… h

2019-03-19 17:07发布

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)

标签: c# logging
3条回答
老娘就宠你
2楼-- · 2019-03-19 17:52

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.

查看更多
再贱就再见
3楼-- · 2019-03-19 17:55

Also, checkout log4net. I never found the EL's logging to be as flexible as log4net. I chose log4net since I was already familiar with using log4j.

protected readonly log4net.ILog LOG = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

Doing it this way, I can get logs like this:

2009-07-15 09:48:51,674 [4420] DEBUG SampleNamespace.SampleClass [(null)] - Sample message you want to output

查看更多
闹够了就滚
4楼-- · 2019-03-19 18:04

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.

查看更多
登录 后发表回答