我应该在我的设计中将项目或应用程序范围的TraceSwitch放在哪里?

时间:2023-01-13 23:01:48

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.

我正在尝试使用System.Diagnostics提供的一些日志记录功能来增强我的程序。由于我的解决方案包含多个项目,我想为整个应用程序创建一个开关,并为每个项目创建一个开关。

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?

从应用程序范围的开关开始,因为在我理解的C#中没有全局变量这样的东西,我怎么能实现这个呢?

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?

这将解决整个项目的1个开关,但这是一个好习惯吗?

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.

关于应用程序范围的切换,我必须在每个其他项目中引用包含GlobalSwitch类的项目,如果可能的话我想避免使用它。

Some clues as to how this can be done the smart way would be very appreciated.

关于如何以聪明的方式做到这一点的一些线索将非常感激。

1 个解决方案

#1


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).

我通常将跟踪开关(和日志功能)包装到一个*日志记录程序集中,向交换机公开静态接口以及将调用正在使用的基础日志功能的静态日志方法(通常是Trace.Write-functions)。

#1


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).

我通常将跟踪开关(和日志功能)包装到一个*日志记录程序集中,向交换机公开静态接口以及将调用正在使用的基础日志功能的静态日志方法(通常是Trace.Write-functions)。