C#条件的记录/追踪 [英] C# conditional logging/tracing

查看:135
本文介绍了C#条件的记录/追踪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要添加日志记录或跟踪我的C#应用​​程序,但我不希望格式化字符串或计算值进行记录,如果日志详细级别设置为如此之低,该消息将不会被记录的开销。

I want to add logging or tracing to my C# application but I don't want the overhead of formatting the string or calculating values to be logged if the log verbosity level is set so low that the message will not be logged.

在C ++中,你可以使用预处理程序定义宏,将防止代码被执行与此相似:

In C++, you can use the preprocessor to define macros that will prevent code from being executed at all like this:

#define VLOG(level,expr) if (level >= g_log.verbosity) { g_log.output << expr; }

用于这样的:

VLOG(5,"Expensive function call returns " << ExpensiveFunctionCall());



你怎么做,在C#?

How do you do that in C#?

我读过微软文档解释了跟踪和调试设备这里,他们声称,使用和#undef DEBUG和#undef TRACE删除所有来自生产可执行跟踪和调试代码,但它真的删除整个电话吗?意思是,如果我写

I've read the Microsoft docs explaining the Trace and Debug facilities here, and they claim that using #undef DEBUG and #undef TRACE removes all tracing and debugging code from the produced executable, but does it really remove the whole call? Meaning, if I write

System.Diagnostics.Trace.WriteLineIf(g_log.verbosity>=5,ExpensiveFunctionCall());



也不会叫我昂贵的功能,如果我取消定义的痕迹?还是拨打电话,,然后决定它不会跟踪任何东西?

it won't call my expensive function if I undefine TRACE? Or does make the call, then decide it won't trace anything?

无论如何,即使它删除它,这是次于C ++的宏,因为我不能让那个又大又丑的呼叫的样子我简单的VLOG在C()调用++,仍然避免评估参数,可以吗?我也不能避免的开销在运行时定义的详细程度下像我一样在C ++中,对吧?

Anyway, even if it does remove it, this is inferior to the C++ macro because I can't make that big ugly call look like my simple VLOG() call in C++ and still avoid evaluating parameters, can I? Nor can I avoid the overhead by defining the verbosity lower at runtime like I can in C++, right?

推荐答案

这些答案的两个(安德鲁·阿诺特的和Brian的)没有回答我的问题的一部分。被施加到跟踪和调试类方法ConditionalAttribute导致如果痕量或调试是#undef'd,包括昂贵的参数评估要除去的方法的所有呼叫。谢谢!

Two of these answers (Andrew Arnott's and Brian's) did answer part of my question. The ConditionalAttribute that is applied to the Trace and Debug class methods causes all calls to the methods to be removed if TRACE or DEBUG are #undef'd, including the expensive parameter evaluation. Thanks!

有关第二部分中,您是否能彻底清除在运行时的所有调用,而不是在编译的时候,我发现在log4net的答案的 FAC 。据他们说,如果你在启动时设置只读属性,则运行将编译远没有通过测试的所有来电!这并不让你启动后改变它,但是这很好,这是不是在编译时删除它们更好。

For the second part, whether you can completely remove all calls at runtime, not at compile time, I found the answer in the log4net fac. According to them, if you set a readonly property at startup time, the runtime will compile away all calls that don't pass the test! This doesn't let you change it after startup but that's fine, it's better than removing them at compile time.

这篇关于C#条件的记录/追踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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