我应该在设计中的哪里放置项目或应用程序范围的 TraceSwitch?
我正在尝试使用 System.Diagnostics 提供的一些日志记录功能来增强我的程序。 由于我的解决方案由多个项目组成,因此我想为整个应用程序创建一个开关,并为每个项目创建一个开关。
现在的问题是,我怎样才能实现这一点以及我应该将开关定义放在哪里?
从应用程序范围的开关开始,由于按照我的理解,C# 中没有全局变量之类的东西,我怎样才能实现这一点呢?
在每个类中放置
static TraceSwitch ApplicationSwitch = new TraceSwitch("Application", "Enables logging in the whole application.");
一次会解决这个问题,还是会创建与类一样多的开关,每个开关都具有相同的名称? (我的猜测是后者)
或者我应该将初始化放在一个单独的类中
static class GlobalSwitch
{
static TraceSwitch Application = new TraceSwitch("Application", "Enables logging in the whole application.");
}
,并从像这样的每个其他类中引用它
public OtherClass
{
static TraceSwitch Application = GlobalSwitch.Application;
}
这将解决整个项目有1个开关的问题,但这是一个好的做法吗?
关于应用程序范围的切换,我必须在每个其他项目中引用包含 GlobalSwitch 类的项目,如果可能的话,我希望避免这种情况。
关于如何以智能方式完成此操作的一些线索将非常感激。
I'm trying to enhance my program with some logging functionality provided by System.Diagnostics
. As my Solution consists of several projects, I wanted to create a switch for the whole application and one for every project.
Now the question is, how can I achieve this and where should I put the switch definition?
Starting with the application wide switch, since there is no such thing as global variables in C# as I understood it, how could I achieve this?
Will putting
static TraceSwitch ApplicationSwitch = new TraceSwitch("Application", "Enables logging in the whole application.");
once in every class solve this or would this rather create as much switches as there are classes, each with the same name? (my guess is the latter)
Or should I put the initialization once in a separate class
static class GlobalSwitch
{
static TraceSwitch Application = new TraceSwitch("Application", "Enables logging in the whole application.");
}
and reference to it from every other class like this
public OtherClass
{
static TraceSwitch Application = GlobalSwitch.Application;
}
This would solve having 1 switch for a whole project, but is this a good practice?
Concerning the application wide switch, I would have to reference the project containing the GlobalSwitch
class in every other project, which I would like to avoid if possible.
Some clues as to how this can be done the smart way would be very appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我通常将跟踪开关(和日志函数)包装到中央日志记录程序集中,向开关公开静态接口以及静态日志方法,这些方法将调用正在使用的底层日志功能(通常是 Trace.Write 函数)。
I usually wrap trace switches (and log functions) into a central logging assembly, exposing a static interface to the switch(es) and also static log methods that will call the underlying log functionality in use (usually Trace.Write-functions).