[Translation] use the log block of Enterprise Library 3.0

Source: Internet
Author: User
Translation

Address: http://www.devx.com/dotnet/Article/36184/0/page/1
Author: thiru thangarathinam (powerful name)
Translation: flanker

Introduction

LogsProgramThe block provides a flexible and scalable log mechanism that you can use in any type of. net programs-including winforms, ASP. NET, and console programs. It provides reusable log classes (also known as monitors) that record log information on a variety of carriers, including databases, XML files, common files, and event records.

As a developer, you only need to select a monitor and specify it in the application configuration file to call basic log functions in the program.

After installing Enterprise Library 3.1, you can see some assembly in the <your directory> \ Microsoft Enterprise Library 3.1-May 2007 \ bin folder.

To use the basic log function, you need to add references to Microsoft. Practices. enterpriselibrary. Common. dll and Microsoft. Practices. enterpriselibrary. Logging. dll. If you want to record the information in the database, you also need to add a reference to Microsoft. Practices. enterpriselibrary. Data. dll. Figure 1 shows the dependency between log blocks.


Figure 1: dependency between log blocks.

Create a simple example

This is a simple example. It demonstrates how to configure a log block to save logs to event records. First, create a C # windows application named loggingblockexample. Add Assembly reference as mentioned above.

Then, import the following log namespace:

Using Microsoft. Practices. enterpriselibrary. logging;

Next, add the configuration option in the application configuration file (App. config) to indicate that the log will be saved in the event record (see list 1 ). All configurations are on the <loggingconfiguration> node, as shown in the following figure:

Listeners -- specifies the monitor to record logs.
Formatters -- an optional element used to specify the log format.
Categorysources-establishes the relationship between specific log categories and monitors. Note: You must specify a categorysources for the defaultcategory attribute of the <loggingconfiguration> element.
Specialsources -- specifies a special monitoring object to process special log entries.

After app. config is completed, the next step is to use the log block to writeCode. First, add a button called btnlogmessage in the Windows form, and add the click event to the button as follows:

Private   Void Btnlogmessage_click ( Object Sender, eventargs E)
... {
// Create a logentry object and set its attributes
Logentry =   New Logentry ();
Entry. eventid =   1 ;
Entry. Priority =   1 ;
Entry. Message =   " This is a test message " ;
Entry. categories. Clear ();
// Note that the default category is general.
Entry. categories. Add ( " General " );
Logger. Write (entry );
MessageBox. Show ( " Log is written " );
}

The above Code uses two log classes: logentry and logger. Logentry indicates a log entry, so it provides some attributes, such as priority, event ID, and log message. Logger provides a class method to write log messages to one or more monitors specified in the configuration file.

Therefore, to write a log message, you should create a logentry object and assign values to its attributes. You can add one or more types to a logentry object to allow suitable monitor records.

Image 2 indicates that after you click "record log" in the sample program, the log messages are saved in the event log.


Image 2 event record: You can use the Application category of Windows event viewer to view recorded log messages.

Use the Enterprise Library Configuration Tool

Although you can manually modify the app. config file, it is easier to use the built-in Configuration tool of Enterprise Library.

Open the Enterprise Library Configuration tool, create a new application, right-click the application configuration and choose new> logging Application Block. (See figure 3)


Figure 3: Enterprise Library Configuration tool: this tool uses a wizard to configure logs.

The configuration of a log block contains four elements: Category sources, special sources, trace listeners, and formatters. By default, the configuration tool creates a formatted EventLog tracelistener monitor that uses text formatter as the default format and adds it to category sources.

The following describes how to configure an XML file log using a configuration tool. First, create an XML monitor, right-click the trace listeners node and select new → XML trace listener. After the monitor is created, change the name attribute of the right panel to c: \ temp \ trace. xml.

The next step is to reference the new monitor. Right-click the all events node and select new → trace listener reference. After adding a monitor reference, change the referencedtracelistener attribute of the right panel to XML trace listener. When you do this, the result should be similar to image 4.


Figure 4 guide logs to the XML monitor: By referencing the XML monitor in all events, you can save any log events in the XML file.

Save the configuration tool settings as app. config. Now you use the newly generated app. config in the C # sample project. The log data will be recorded in the XML log file. (See Figure 5)


Figure 5 xml log: This is a log recorded XML file. Note that there are two main nodes (System and applicationdata) that respectively Save System Properties and logs.

Use a database for log storage

You already know how to write logs in event records and XML files. This is suitable for most simple applications, but for more complex applications, you may want to record logs in a stable storage, such as the SQL Server database. Logs can also be easily queried in the database. The log block provides a database monitor to record logs to the database.

To use database logs, you must first execute an SQL script (provided by the Enterprise Library) to create a database. Run loggingdatabase in the <your directory> \ entlib3src \ appblocks \ SRC \ Logging \ tracelisteners \ database \ scripts folder. SQL file, which will create a database named logging in your SQL Server.

Now, you need to modify the app. config file to use the database monitor. You also need to specify the database connection string. The database app. config file in the Code is a complete configuration file.

Note: before using the app. config file, make sure that you have changed the <connectionstrings> element connection string in the database app. config file to match your own database.

Next, open the winforms application, replace the app. config file, and run the program again. After clicking this button, you can view the log entries in the log table of the logging database.

Implement custom Monitor

If the built-in monitor cannot meet your requirements, the log block allows you to implement custom monitor. The custom monitor inherits from the customtracelistener class. But these are beyond thisArticleScope, you can get more information in this msdn article.

You have learned how to use Log block to build a flexible and easy-to-maintain log system in. net programs. Use configuration files and simple code to record logs in files, event records, and databases. Of course, configuration files are a little annoying, but it is better than writing duplicate code or even changing the code to convert the storage. In addition, the Enterprise Library Configuration tool simplifies the configuration through the wizard. Now you can add great logs to your application.

About the author

thiru thangarathinam works for intel in Arizona. He is an MVP of Microsoft and is good at using. Net-related technologies to construct, design, and develop distributed enterprise-level applications. He is the author of professional ASP. NET 2.0 XML and professional ASP. NET 2.0 databases, and has written a series of books on. NET related technologies. He is also an active contributor to online technical publications. Email Contact.

attachment

enterprise_library_logging.zip (18kb)

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.