Use of Trace, Debug, and TraceSource, and log design

Source: Internet
Author: User
Tags assert switches system log

Summary of this chapter:

1:trace and Debug differences

2: What is listeners

3: Tracking Switch

3.1: Use BooleanSwitch switch

3.2: Use TraceSwitch switch

4: Use TraceSource instead of trace and

5: Design a log system

6: About EventLog

The. NET Framework namespace System.Diagnostics contains trace, Debug, and TraceSource classes for tracking execution processes, as well as Process, EventLog, and Performanceco for parsing code Unter class.

Tracing is a way to monitor the execution of an application while it is running. When you develop a. NET Framework application, you can add tracing and debugging instrumentation to it, and you can use it when you develop your application and after you deploy your application. With the Trace and Debug classes, you can log information about errors and application execution to a log, text file, or other device for subsequent analysis.

The following is a list of six Debug members and trace methods that write trace information.

Assert: The specified text, or call stack if no text is specified. The output is written only if the condition specified as a parameter in the Assert statement is false .

Fail: The specified text, or call stack if no text is specified.

Write: the specified text.

WriteIf: The specified text if the condition specified as a parameter in the WriteIf statement is met.

WriteLine: The specified text and a carriage return.

WriteLineIf: Specifies the text and a carriage return if the condition specified as a parameter in the WriteLineIf statement is met.

1:trace and debug Differences

The trace and Debug classes are basically the same, except that the procedure and function of the trace class are by default compiled into a release version.

2: What is listeners

The Listenters property, which is the Tracelistenercollection type (TraceSource class and TraceListener Class), controls the direction of the trace information output for the class attribute, which can be the console ( TextWriterTraceListener (new Console.Out)), File (Add (TextWriterTraceListener) (New IO. File.createtext ("Output.txt")) and so on. The members of the Listenters collection include Textwritertracelistener,defaulttracelistener,eventlogtracelistener,webpagetracelistener, and so on. And TextWriterTraceListener's subclasses have Consoletracelistener, Delimitedlisttracelistener,xmlwritertracelistener, EventSchemaTraceListener.

You can generate custom results by implementing your own listeners. All custom listeners should support six methods in the initial table of the article.

The following example shows that the output message will be recorded in the console, TXT file, and the system log.

            TextWriterTraceListener TR1 = new TextWriterTraceListener (System.Console.Out);
            DEBUG.LISTENERS.ADD (TR1);
            TextWriterTraceListener tr2 = new TextWriterTraceListener (System.IO.File.CreateText ("output.txt"));
            DEBUG.LISTENERS.ADD (TR2);
            EventLogTraceListener TR3 = new EventLogTraceListener ();
            DEBUG.LISTENERS.ADD (TR3);

3: Tracking Switch

In addition to specifying listener, you need to specify a trace switch to control whether the message is exported. Trace switches enable, disable, and filter trace output.

The Framework provides three types of trace switches: The BooleanSwitch class, the TraceSwitch class, and the Sourceswitch class. BooleanSwitch is the simplest trace switch that specifies whether to output messages. The TraceSwitch and Sourceswitch classes enable trace switches for specific trace levels to display trace or TraceSource messages that are specified for the level and all levels below it. 3.1: Use booleanswitch switch

The following are examples of using BooleanSwitch:

            TextWriterTraceListener TR1 = new TextWriterTraceListener (System.Console.Out);
            DEBUG.LISTENERS.ADD (TR1);
            TextWriterTraceListener tr2 = new TextWriterTraceListener (System.IO.File.CreateText ("output.txt"));
            DEBUG.LISTENERS.ADD (TR2);
            EventLogTraceListener TR3 = new EventLogTraceListener ();
            DEBUG.LISTENERS.ADD (TR3);

            bool Somebizcondition = true;
            BooleanSwitch bs = new BooleanSwitch ("DataMessageSwitch", "DataMessageSwitch des");
            Bs. Enabled = true;
            Debug.WriteLineIf (somebizcondition, "Log ...");
            Debug.flush ();

Bs. Enabled is set to TRUE or false and does not cause the program to automatically decide whether or not to output information.

If you do not use the code method, but instead use the configuration file, after the <configuration> tag, but add the corresponding XML before the </configuration> tag to configure your switch. As follows:

<system.diagnostics>
   <switches>
      <add name= "Datamessagesswitch" value= "1"/>
   </ Switches>
</system.diagnostics>
3.2: Use traceswitch switch

The TraceSwitch class can use the trace switch to filter messages, and to get or set the switch level through the Levels property. 0, 1, 2, 3, and 4 correspond to off,Error,Warning,Info , and Verboserespectively. Any number greater than 4 will be treated as a Verbose, and any number less than 0 will be treated as off.

The following example, in code, demonstrates using TraceSwitch to set the trace switch:

            TextWriterTraceListener TR1 = new TextWriterTraceListener (System.Console.Out);
            DEBUG.LISTENERS.ADD (TR1);
            TextWriterTraceListener tr2 = new TextWriterTraceListener (System.IO.File.CreateText ("output.txt"));
            DEBUG.LISTENERS.ADD (TR2);
            EventLogTraceListener TR3 = new EventLogTraceListener ();
            DEBUG.LISTENERS.ADD (TR3);

            bool Somebizcondition = true;
            TraceSwitch ts = new TraceSwitch ("Myswitch", "in the Config file");
            Ts. level = Tracelevel.verbose;
            Debug.WriteLineIf (TS. TraceError && somebizcondition, "Error!!!");
            Debug.WriteLineIf (TS. Tracewarning && somebizcondition, "Warning!!!");
            Debug.WriteLineIf (TS. Traceinfo && somebizcondition, "Info!!!");
            Debug.WriteLineIf (TS. Traceverbose && somebizcondition, "Verbose!!!");
            Debug.flush ();

Using XML to configure, as follows:

<system.diagnostics>
   <switches>
      <add name= "Myswitch" value= "1"/>
   </switches>
</system.diagnostics>

4: Use TraceSource instead of trace and debug

Starting with FRAMEWORK2.0, trace and debug are not recommended, instead of tracesouce. TraceSource is intended to be used as an enhanced tracking system and can be used in lieu of static methods of older trace and Debug trace classes. The familiar trace and Debug classes still exist, but the recommended practice is to use the TraceSource class for tracing.

The following example shows the use of code to implement the output of a message:

        private static TraceSource MySource = new TraceSource ("Tracesourceapp");
            static void Main (string[] args) {mysource.switch = new Sourceswitch ("Sourceswitch", "Error");

            MySource.Listeners.Remove ("Default");
            TextWriterTraceListener textlistener = new TextWriterTraceListener ("MyListener.log"); Textlistener.traceoutputoptions = Traceoptions.datetime |
            Traceoptions.callstack;
            Textlistener.filter = new Eventtypefilter (sourcelevels.error);
            
            MYSOURCE.LISTENERS.ADD (TextListener);
            Consoletracelistener console = new Consoletracelistener (false); Console.
            Filter = new Eventtypefilter (sourcelevels.information); Console.
            Name = "Console";
            MYSOURCE.LISTENERS.ADD (console);

            Activity1 ();
            Set the filter settings for the//console trace listener. mysource.listeners["Console"]. Filter = new EVENTTYPEFIlter (sourcelevels.critical);

            Activity2 (); 
            Allow the trace source to send messages to//listeners for all event types.

            MySource.Switch.Level = Sourcelevels.all;
            Change the filter settings for the console trace listener. mysource.listeners["Console"].
            Filter = new Eventtypefilter (sourcelevels.information);
            Activity3 ();

            Mysource.close ();
        Return
            } static void Activity1 () {mysource.traceevent (Traceeventtype.error, 1, "Error message.");
        Mysource.traceevent (traceeventtype.warning, 2, "Warning message."); static void Activity2 () {mysource.traceevent (traceeventtype.critical, 3, "Critical message.)
            ");
        Mysource.traceinformation ("informational message.");
} static void Activity3 () {mysource.traceevent (Traceeventtype.error, 4, "Error message.");            Mysource.traceinformation ("informational message."); }

The above code, if implemented using a configuration file, is as follows:

  <system.diagnostics>
    <sources>
      <source name= "Tracesourceapp" switchname= "Sourceswitch" Switchtype= "System.Diagnostics.SourceSwitch" >
        <listeners>
          <add name= "Console" type= " System.Diagnostics.ConsoleTraceListener ">
            <filter type=" System.Diagnostics.EventTypeFilter " Initializedata= "Warning"/>
          </add>
          <add name= "MyListener" System.Diagnostics.TextWriterTraceListener "Initializedata=" MyListener.log " 
               traceoutputoptions=" CallStack " >
            <filter type= "System.Diagnostics.EventTypeFilter" Initializedata= "Error" ></filter>
          </add>
          <remove name= "Default"/>
        </listeners>
      </source>
    </sources >
    <switches>
      <add name= "Sourceswitch" value= "Warning"/>
    </switches>
  </system.diagnostics>

The corresponding code portion of the configuration file implementation is:

        private static TraceSource MySource = new TraceSource ("Tracesourceapp");
        static void Main (string[] args)
        {
            Activity1 ();
            Activity2 ();
            Activity3 ();
            Mysource.close ();
            return;
        }
        static void Activity1 ()
        {
            mysource.traceevent (traceeventtype.error, 1, "Error message.");
            Mysource.traceevent (traceeventtype.warning, 2, "Warning message.");
        }
        static void Activity2 ()
        {
            mysource.traceevent (traceeventtype.critical, 3, "Critical message.");
            Mysource.traceinformation ("informational message.");
        }
        static void Activity3 ()
        {
            mysource.traceevent (Traceeventtype.error, 4, "Error message.");
            Mysource.traceinformation ("informational message.");
        }

5: Design a log system

With the above knowledge, we can design an application's log system (yes, we don't need log4net). Let's assume the most basic function of this log system:

1, the date to create a log name, so as to avoid all the history log written to a file;

2, can be configured to output the log category, such as warning or error;

3, can configure the desired log content: such as stacktrace or error information;

Ideas:

1. In the application startup code, set the filename. The configuration file cannot be used because the file name is dynamically generated according to the date;

2, other configuration can be configured to achieve the file;

3, do IT;

6: About EventLog

About EventLog is a feature that I do not like, more content can refer to: HTTP://MSDN.MICROSOFT.COM/ZH-CN/LIBRARY/AAAXK5BX (vs.80). aspx

Practice:

1.You are using the Microsoft Visual Studio, returns a string, examine the output of a method.
You are assign the output of the method to a string variable named FName. You are need to write a-code segment that
Prints the "following on a". "Test Failed." The value of FName if the value of FName does
Not equal "John" your also need to ensure this code segment simultaneously facilitates uninterrupted
of the application. Which code segment should use?
A. Debug.Assert (FName = = "John", "Test FaileD.", FName);
B. Debug.WriteLineIf (fName!= "John", FName, "Test Failed");
C. if (fName!= "John") {Debug.Print ("Test FaileD.");      Debug.Print (FName); }
D. if (fName!= "John") {Debug.WriteLine ("Test FaileD.");     Debug.WriteLine (FName); }
Answer:b

17.You are testing a newly developed method named Persisttodb. This method accepts a parameter of type
EventLogEntry. This method does does return a value. You are need to create a code segment which helps you to test the
Method. The code segment must read entries from the Application log to local computers and then pass the entries
On to the Persisttodb method. The code block must pass only events of type Error or Warning from the source
MySource to the Persisttodb method. Which code segment should use?
A. EventLog mylog = new EventLog ("Application", ".");
foreach (EventLogEntry entry in mylog.entries)
{if (entry).     Source = = "MySource") {Persisttodb (entry); }  }
B. EventLog mylog = new EventLog ("Application", ".");
Mylog.source = "MySource";
foreach (EventLogEntry entry in mylog.entries) {
if (entry. EntryType = = (EventLogEntryType.Error & eventlogentrytype.warning))
{Persisttodb (entry); }}

C. EventLog mylog = new EventLog ("Application", ".");
foreach (EventLogEntry entry in mylog.entries)
{if (entry). Source = "MySource")
{if (entry). EntryType = = EventLogEntryType.Error | | Entry. EntryType = = eventlogentrytype.warning)
{Persisttodb (entry);} } }
D. EventLog mylog = new EventLog ("Application", ".");
Mylog.source = "MySource";
foreach (EventLogEntry entry in mylog.entries)
{if (entry). EntryType = = EventLogEntryType.Error | | Entry. EntryType = = eventlogentrytype.warning)
{Persisttodb (entry);}
Answer:c

Turn from: http://www.cnblogs.com/luminji/archive/2010/10/26/1861316.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.