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

发布于 2024-07-19 02:12:53 字数 905 浏览 6 评论 0原文

我正在尝试使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沉睡月亮 2024-07-26 02:12:53

我通常将跟踪开关(和日志函数)包装到中央日志记录程序集中,向开关公开静态接口以及静态日志方法,这些方法将调用正在使用的底层日志功能(通常是 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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文