我将使用C#创建简单的记录器,因此可以将其用作最佳实践的设计模式是什么? [英] I am going to create simple logger using C# so what are the design patterns I can use to create this as best practice?

查看:100
本文介绍了我将使用C#创建简单的记录器,因此可以将其用作最佳实践的设计模式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常使用记录器将给定的消息(错误,警告或信息)记录到日志文件(简单的文本文件或xml)中

Usually loggers are used to log given message (error, warnings or information) to a log file (simple text file or xml)

推荐答案

好吧,显而易见的选择是Strategy(可以配置为使用不同输出选项的一个记录器)和Composite(在多个输出部分上进行多路输出)。

Well, the obvious choces are Strategy (one logger that can be configured to use different output options) and Composite (multiplex output over several output outions).

像这样(在Java中):

So something like this (in Java):

public class Logger {

  public interface LogOutput {
    void out(final String s);
  }

  // Composite - use to send logging to several destinations
  public LogOutput makeComposite(final LogOutput... loggers) {
    return new LogOutput() {
      void out(final String s) {
        for (final LogOutput l : loggers) {
          l.out(s);
        }
      }
    }
  }


  private static currentLogger = new LogOutput() {
    void out(final String s) {
       // Do nothing as default - no strategy set
    }
  }

  public static log(final String s) {
    currentLogger.out(s);
  }


  // Strategy: Set a new strategy for output
  public static setLogger(final LogOutput l) {
    currentLogger = l;
  }

}

这篇关于我将使用C#创建简单的记录器,因此可以将其用作最佳实践的设计模式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆