复合应用的最佳日志记录方法?

Dav*_*man 15 c# logging log4net prism

我正在创建一个复合WPF(Prism)应用程序,它有几个不同的项目(Shell,模块等).我正准备使用Log4Net实现日志记录.似乎有两种方法来设置日志记录:

  • 让Shell项目完成所有实际的日志记录.它获取对Log4Net的引用,其他项目触发复合事件,让Shell知道它需要记录一些东西.这些项目仅针对在Shell的app.config文件(DEBUG,ERROR等)中打开日志记录的级别触发事件,以免降低性能.

  • 为每个项目(包括模块)提供Log4Net引用,让项目自己记录到公共日志文件,而不是向Shell发送消息以进行日志记录.

哪种方法更好?或者,我应该考虑另一种方法吗?谢谢你的帮助.

Met*_*urf 18

登录Prism的最简单方法是覆盖Bootstrapper中LoggerFacade属性.通过覆盖,只要记录器实现接口,您就可以使用任何所需的配置传入任何Logger的实例.LoggerFacadeILoggerFacade

我发现以下内容可以很好地用于日志记录(我正在使用Enterprise Libary Logging块,但是为Log4Net应用类似的东西应该是直截了当的):

在你的Shell中创建一个Boostrapper:

-My Project
  -Shell Module (add a reference to the Infrastructure project)
    -Bootstrapper.cs
Run Code Online (Sandbox Code Playgroud)

在基础结构项目中创建日志记录适配器,即:

-My Project
  -Infrastructure Module
    -Adapters
      -Logging
        -MyCustomLoggerAdapter.cs
        -MyCustomLoggerAdapterExtendedAdapter.cs
        -IFormalLogger.cs
Run Code Online (Sandbox Code Playgroud)

MyCustomLoggerAdapter类将被用来覆盖在引导程序的"LoggerFacade"属性.它应该有一个默认的contstructor来告知所有内容.

注意:通过覆盖LoggerFacadeBootstrapper中的属性,您将为Prism提供日志记录机制,以用于记录其自己的内部消息.您可以在整个应用程序中使用此记录器,也可以扩展记录器以获得功能更全面的记录器.(见MyCustomLoggerAdapterExtendedAdapter/ IFormalLogger)

public class MyCustomLoggerAdapter : ILoggerFacade
{

    #region ILoggerFacade Members

    /// <summary>
    /// Logs an entry using the Enterprise Library logging. 
    /// For logging a Category.Exception type, it is preferred to use
    /// the EnterpriseLibraryLoggerAdapter.Exception methods."
    /// </summary>
    public void Log( string message, Category category, Priority priority )
    {
        if( category == Category.Exception )
        {
            Exception( new Exception( message ), ExceptionPolicies.Default );
            return;
        }

        Logger.Write( message, category.ToString(), ( int )priority );
    }

    #endregion


    /// <summary>
    /// Logs an entry using the Enterprise Library Logging.
    /// </summary>
    /// <param name="entry">the LogEntry object used to log the 
    /// entry with Enterprise Library.</param>
    public void Log( LogEntry entry )
    {
        Logger.Write( entry );
    }

    // Other methods if needed, i.e., a default Exception logger.
    public void Exception ( Exception ex ) { // do stuff }
}
Run Code Online (Sandbox Code Playgroud)

MyCustomLoggerAdapterExtendedAdapter从dervied MyCustomLoggerAdapter,可以为更全面的记录器提供额外的构造函数.

public class MyCustomLoggerAdapterExtendedAdapter : MyCustomLoggerAdapter, IFormalLogger
{

    private readonly ILoggingPolicySection _config;
    private LogEntry _infoPolicy;
    private LogEntry _debugPolicy;
    private LogEntry _warnPolicy;
    private LogEntry _errorPolicy;

    private LogEntry InfoLog
    {
        get
        {
            if( _infoPolicy == null )
            {
                LogEntry log = GetLogEntryByPolicyName( LogPolicies.Info );
                _infoPolicy = log;
            }
            return _infoPolicy;
        }
    }

    // removed backing code for brevity
    private LogEntry DebugLog... WarnLog... ErrorLog


    // ILoggingPolicySection is passed via constructor injection in the bootstrapper
    // and is used to configure various logging policies.
    public MyCustomLoggerAdapterExtendedAdapter ( ILoggingPolicySection loggingPolicySection )
    {
        _config = loggingPolicySection;
    }


    #region IFormalLogger Members

    /// <summary>
    /// Info: informational statements concerning program state, 
    /// representing program events or behavior tracking.
    /// </summary>
    /// <param name="message"></param>
    public void Info( string message )
    {
        InfoLog.Message = message;
        InfoLog.ExtendedProperties.Clear();
        base.Log( InfoLog );
    }

    /// <summary>
    /// Debug: fine-grained statements concerning program state, 
    /// typically used for debugging.
    /// </summary>
    /// <param name="message"></param>
    public void Debug( string message )
    {
        DebugLog.Message = message;
        DebugLog.ExtendedProperties.Clear();
        base.Log( DebugLog );
    }

    /// <summary>
    /// Warn: statements that describe potentially harmful 
    /// events or states in the program.
    /// </summary>
    /// <param name="message"></param>
    public void Warn( string message )
    {
        WarnLog.Message = message;
        WarnLog.ExtendedProperties.Clear();
        base.Log( WarnLog );
    }

    /// <summary>
    /// Error: statements that describe non-fatal errors in the application; 
    /// sometimes used for handled exceptions. For more defined Exception
    /// logging, use the Exception method in this class.
    /// </summary>
    /// <param name="message"></param>
    public void Error( string message )
    {
        ErrorLog.Message = message;
        ErrorLog.ExtendedProperties.Clear();
        base.Log( ErrorLog );
    }

    /// <summary>
    /// Logs an Exception using the Default EntLib Exception policy
    /// as defined in the Exceptions.config file.
    /// </summary>
    /// <param name="ex"></param>
    public void Exception( Exception ex )
    {
        base.Exception( ex, ExceptionPolicies.Default );
    }

    #endregion


    /// <summary>
    /// Creates a LogEntry object based on the policy name as 
    /// defined in the logging config file.
    /// </summary>
    /// <param name="policyName">name of the policy to get.</param>
    /// <returns>a new LogEntry object.</returns>
    private LogEntry GetLogEntryByPolicyName( string policyName )
    {
        if( !_config.Policies.Contains( policyName ) )
        {
            throw new ArgumentException( string.Format(
              "The policy '{0}' does not exist in the LoggingPoliciesCollection", 
              policyName ) );
        }

        ILoggingPolicyElement policy = _config.Policies[policyName];

        var log = new LogEntry();
        log.Categories.Add( policy.Category );
        log.Title = policy.Title;
        log.EventId = policy.EventId;
        log.Severity = policy.Severity;
        log.Priority = ( int )policy.Priority;
        log.ExtendedProperties.Clear();

        return log;
    }

}


public interface IFormalLogger
{

    void Info( string message );

    void Debug( string message );

    void Warn( string message );

    void Error( string message );

    void Exception( Exception ex );

}
Run Code Online (Sandbox Code Playgroud)

Bootstrapper中:

public class MyProjectBootstrapper : UnityBootstrapper
{

  protected override void ConfigureContainer()
  {
    // ... arbitrary stuff

    // create constructor injection for the MyCustomLoggerAdapterExtendedAdapter
      var logPolicyConfigSection = ConfigurationManager.GetSection( LogPolicies.CorporateLoggingConfiguration );
      var injectedLogPolicy = new InjectionConstructor( logPolicyConfigSection as LoggingPolicySection );

      // register the MyCustomLoggerAdapterExtendedAdapter
      Container.RegisterType<IFormalLogger, MyCustomLoggerAdapterExtendedAdapter>(
              new ContainerControlledLifetimeManager(), injectedLogPolicy );

  }

    private readonly MyCustomLoggerAdapter _logger = new MyCustomLoggerAdapter();
    protected override ILoggerFacade LoggerFacade
    {
        get
        {
            return _logger;
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

最后,要使用任一记录器,您需要做的就是为类的构造函数添加适当的接口,UnityContainer将为您注入记录器:

public partial class Shell : Window, IShellView
{
    private readonly IFormalLogger _logger;
    private readonly ILoggerFacade _loggerFacade;

    public Shell( IFormalLogger logger, ILoggerFacade loggerFacade )
    {
        _logger = logger;
        _loggerFacade = loggerFacade

        _logger.Debug( "Shell: Instantiating the .ctor." );
        _loggerFacade.Log( "My Message", Category.Debug, Priority.None );

        InitializeComponent();
    }


    #region IShellView Members

    public void ShowView()
    {
        _logger.Debug( "Shell: Showing the Shell (ShowView)." );
         _loggerFacade.Log( "Shell: Showing the Shell (ShowView).", Category.Debug, Priority.None );
       this.Show();
    }

    #endregion

}
Run Code Online (Sandbox Code Playgroud)

我认为您不需要单独的模块来执行日志记录策略.通过将日志记录策略添加到基础结构模块,所有其他模块将获得所需的引用(假设您将基础结构模块添加为对其他模块的引用).通过将记录器添加到Boostrapper,您可以让UnityContainer根据需要注入日志记录策略.

在CodePlex上的CompositeWPF contrib项目中有一个简单的uisng Log4Net示例.

HTH的