15

I want to build my log4net logger in my MVC controller abstract base class like so:

protected static readonly ILog Log = LogManager.GetLogger(typeof(AuthorizedController));

In this manner I can define the logger once and be done with it. The only problem is that the logger attribute in the log output will always be AuthorizedController, and if I have FooController inherited from AuthorizedController I'd like the log output to reflect that.

What would be a good KISS, DRY, and efficient way do doing this?

4

4 に答える 4

20

I'm not sure how expensive the call to LogManager.GetLogger() is, but I suspect that there is some clever caching and/or lazy initialization in the log4net system that keeps requested instances available for quick retrieval. After all, there is no reason why calling LogManager.GetLogger() twice with the same type parameter would return a different instance.

That said, perhaps replacing the field with the following property will suffice.

protected ILog Logger
{
    get { return LogManager.GetLogger(GetType()); }
}

GetType() is virtual and overloaded so each concrete type will supply its type when this property is called.

于 2012-08-17T15:32:04.910 に答える
4

As Steve Guidi suggested - use GetType to create logger for specific instance of type. You can save reference to instance of logger which gets calling LogManager.GetLogger in backing field:

    private ILog _log;
    protected ILog Log => _log ?? (_log = LogManager.GetLogger(GetType()));
于 2016-10-26T19:15:27.913 に答える
3

I did something similar by using NInject as an IoC container, but I suppose you can grab the idea to use with your own container. Basically I inject ILog on the requesting types constructor, but instead of binding to an instance, I bind it to a provider.

  kernel.Bind<ILog>().ToProvider<MyProvider>();

public object Create(IContext context)
{
    return LogManager.GetLogger(context.Request.Target.Member.DeclaringType);
}

so each type receive a logger that is the same as doing GetLogger(GetType()) in the constructor.

于 2012-08-17T15:34:40.350 に答える
0

静的ロガー(または一般的に静的インスタンス)を持つことは悪い習慣です。関係のないコンポーネント間の望ましくない結合につながる可能性があります。

ゲームに依存性注入/制御の反転フレームワークを追加することを検討する必要があります。ロガーをクラスのコンストラクターに注入してもらいます。ほとんどのフレームワークでは、さまざまなコンテキストでさまざまな実装を定義できます。

キャッスルウィンザーを製品に使用しています

この投稿を見て、DIと一緒にロギングを使用する例を見つけることもできます

于 2012-08-17T15:35:45.547 に答える