单例还是静态记录器? [英] Singleton or Static Logger?

查看:44
本文介绍了单例还是静态记录器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前的C#应用​​程序是一个可执行文件(EXE)和几个DLL(所以有多个二进制文件),我想创建一个LOGGER(一些简单的自定义记录器,无论从何处调用它都写入一个文本文件)-并且所有二进制文件(exe和dll的文件)中都应有此文件-请注意,它是一个单线程应用程序.

My current C# application is a single executable (EXE) and a few DLLs (so multiple binaries) and I want to create a LOGGER (some simple custom logger that writes to a single text file no matter where it is being called from - and this should be available in all the binaries (exe and dll's) - note that it is a single threaded application.

现在我有一个DLL(Logger),它有一个类(Log)以及一个记录日志的方法(trace),每个项目都添加对该DLL(Logger)的引用,并创建自己的实例(传递文件)名称),然后调用.Trace(...)函数-工作正常...

Right now I have a DLL (Logger) and it has a class (Log) with a method (trace) which logs, each project adds a reference to this DLL (Logger) and creates its own instance (pass in a file name) and then calls the .Trace(...) function - works fine ...

但是我宁愿不必创建许多不同的跟踪文件(每个项目最少一个),并且每次都必须创建一个Logger的新实例似乎是重复的……所以我一直在考虑创建STATIC logger类或使用辛格尔顿...我只是不确定哪个是最好的,为什么...

But I would rather not have to create many different trace files (minimum one per project) and having to create a new instance of Logger each time seems repetitive ... So I was looking into either creating a STATIC logger class or using a SINGLTON ... I am just not sure which is best and why ...

我希望有人可以为此指出正确的方向,什么是创建可被许多项目(引用)使用的记录器类(将是其自己的DLL)的最佳方法,它们应该全部写入相同的日志文件...?

I was hoping someone could maybe point me in the right direction on this, what is the best way to create a logger class (it will be its own DLL) that will be used by many projects (referenced) and they should all write to the same log file...?

任何帮助将不胜感激.谢谢,

Any help would be much appreciated. Thanks,

推荐答案

Singleton Static 记录器之间进行选择的方式与您始终在两者之间进行选择的方式相同:是否希望能够覆盖方法(或使用 Logging 接口)?如果使用单例,则有机会覆盖方法来更改功能.您甚至可以将行为抽象为界面背后的内容.

You choose between Singleton and Static logger the same way you always choose between the two: Do you want to be able to override methods (or use a Logging interface)? If you use a singleton, you have the opportunity to override methods to change functionality. You can even abstract the behavior away behind an interface.

使用静态类,您现在将永远与该类联系在一起,任何更改都会影响到每个人.

With a static class you are now and forever tied to that class, and any changes affect everyone.

在处理我自己的系统时,我已转向单例实例对象.它提供了静态类无法提供的灵活性.

When dealing with my own systems, i have moved towards singleton instanced objects. It gives a level of flexibility not available with static classes.

这篇关于单例还是静态记录器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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