C# 日志设计 : Extension method, 的替代方案?

标签 c# logging interface extension-methods

我想编写一个记录器,可以轻松地将其附加到我当前项目中的任何类中。对于开发来说,将消息记录到控制台会很方便,而在最终版本中我想记录到文件或其他东西。人们应该能够通过编辑几行代码(最好是一个设置文件)来更改行为。

到目前为止我所拥有的是这个类结构:

public interface ILogger {
    void LogMessage(String message);
    // ... other logging functions (exceptions, time etc.) don't matter here
};

public interface ILoggable { };

public static class LoggingProvider {
    private static ILogger logger = ConsoleLogger.handle;
        public static void LogMessage(this ILoggable obj, String message) {
        logger.LogMessage(message);
    }
}


public sealed class NullLogger : ILogger {
        // A logger that does nothing..
};

public sealed class FileLogger : ILogger {
    // A logger that writes to a file..
};

public sealed class ConsoleLogger : ILogger {
    #region Console Allocation
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool AllocConsole();
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool FreeConsole();
    #endregion

    #region Singleton implementation
    private static Object cs = new Object();
    private static ILogger instance = null;
    private ConsoleLogger() {
        AllocConsole();
    }
    ~ConsoleLogger() {
        FreeConsole();
    }
    public static ILogger handle {
        get {
            lock ( cs ) { if ( instance == null ) instance = new ConsoleLogger(); }
            return instance;
        }
    }
    #endregion

    #region ILogger Member
    public void LogMessage(string message) {
        lock ( cs ) {
            String logString = getTimeString();
            logString += ( " -> \t " + message );
            Console.WriteLine(logString);
        }
    }
    #endregion

    #region Helper functions
    // ...
    #endregion
};

现在,我可以拥有任何想要实现 ILoggable 的类,并且通过扩展方法 LogingProvider.LogMessage 我可以调用 this.LogMessage( “...”) 在这些类中。如果是 C++,我只会使用私有(private)继承。

现在的设计是好是坏?有什么我可以改进的吗?有没有一种方法可以为类提供日志记录功能,而无需扩展方法,但同样需要进行很少的更改?

最佳答案

乍一看,你的设计似乎有点过度设计。在这个方法中:

public static void LogMessage(this ILoggable obj, String message) {
    logger.LogMessage(message);
}

根本不使用ILoggable obj。那你为什么需要它呢?为什么不直接拥有:

public static void LogMessage(String message) {
    logger.LogMessage(message);
}

并将其命名为LoggingProvider.LogMessage(...)

顺便说一句,请查看 Log4Net ,这是日志记录功能的行业标准实现。

关于C# 日志设计 : Extension method, 的替代方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21882554/

相关文章:

node.js - 将 Azure 应用服务的 stdout 和 stderr 日志存储到 Azure Blob 存储中

go - 基于接口(interface)抽象实现一个 'Stringer'

c - Fortran 和 c 在源代码如何接口(interface)和编译在一起方面的细微差别

c# - c# string 如何计算它自己的值?

java - 是否有任何关于如何以编程方式配置 logback 的文档?

c# - Akka.NET 无法识别我的自定义记录器并默认为 BusLogger

java - 实现接口(interface)方法(没有显式实现该接口(interface))的类是否扩展了该特定接口(interface)?

c# - 如何检测我的应用程序是否在 Windows 10 上运行

c# - 如何为自定义类中的 List<T> 属性创建索引访问器?

c# - Microsoft.TeamTest.targets 中的 MSBuild NullReferenceException