AppDiag类

AppDiag
#define TRACE
//#undef TRACE
#define PerfMonitor
using System;
using System.Diagnostics;
using System.Reflection;
using System.Web;
using System.Threading;

namespace Rocky
{
public static class AppDiag
{
public const string DebugSymbal = "DEBUG";
#if TRACE
/// <summary>
/// Trace Enhanced tracing functionality to consolidate system and http tracing log and provide support for trace switches.
/// </summary>
private static readonly TraceSwitch traceSwitch = new TraceSwitch("AppTrace", "Runtime Trace");
#endif

[Conditional(DebugSymbal)]
public static void GuardArgument(object arg)
{
GuardArgument(arg,
string.Empty);
}
[Conditional(DebugSymbal)]
public static void GuardArgument(object arg, string paramName)
{
if (arg == null)
{
try
{
System.Diagnostics.Debug.Assert(
false, paramName);
#if TRACE
System.Diagnostics.Trace.Assert(
false, paramName);
#endif
}
catch
{

}
throw new ArgumentNullException(paramName);
}
}

[Conditional(DebugSymbal)]
public static void GuardArgument(bool ifTrue)
{
GuardArgument(ifTrue,
string.Empty);
}
[Conditional(DebugSymbal)]
public static void GuardArgument(bool ifTrue, string message)
{
if (ifTrue)
{
try
{
System.Diagnostics.Debug.Assert(
false, message);
#if TRACE
System.Diagnostics.Trace.Assert(
false, message);
#endif
}
catch
{

}
throw new ArgumentException(message);
}
}

[Conditional(DebugSymbal)]
public static void Guard<T>(bool condition) where T : Exception
{
Guard
<T>(condition, string.Empty);
}
[Conditional(DebugSymbal)]
public static void Guard<T>(bool condition, string message) where T : Exception
{
if (condition)
{
try
{
System.Diagnostics.Debug.Assert(
false, message);
#if TRACE
System.Diagnostics.Trace.Assert(
false, message);
#endif
}
catch
{

}
throw (T)Activator.CreateInstance(typeof(T), message);
}
}

[Conditional(DebugSymbal)]
public static void Guard<T>(Func<bool> predicate) where T : Exception
{
Guard
<T>(predicate, string.Empty);
}
[Conditional(DebugSymbal)]
public static void Guard<T>(Func<bool> predicate, string message) where T : Exception
{
if (predicate())
{
try
{
System.Diagnostics.Debug.Assert(
false, message);
#if TRACE
System.Diagnostics.Trace.Assert(
false, message);
#endif
}
catch
{

}
throw (T)Activator.CreateInstance(typeof(T), message);
}
}

[Conditional(DebugSymbal)]
public static void Trace(string message)
{
Trace(TraceLevel.Info, message);
}
[Conditional(DebugSymbal)]
public static void Trace(TraceLevel level, string message)
{
if (level <= traceSwitch.Level)
{
try
{
System.Diagnostics.Trace.WriteLine(message);
HttpContext httpContext
= HttpContext.Current;
if (httpContext != null)
{
if (level == TraceLevel.Error)
{
httpContext.Trace.Warn(message);
}
else
{
httpContext.Trace.Write(message);
}
}
}
catch
{
// Do nothing: do not corrupt the current error with a failure to trace an error
}
}
}
}
}
原文地址:https://www.cnblogs.com/Googler/p/2005935.html