Use and configuration of entlib5.0 log application block (logging)

Source: Internet
Author: User
1. Basic concepts of logging Block

The use of log components in entlib 5.0 is much more troublesome than log4net and common. logging, and must be explicitly referenced.

Microsoft. Practices. enterpriselibrary. Common
Microsoft. Practices. enterpriselibrary. Logging
Microsoft. Practices. servicelocation
In fact, Microsoft. Practices. servicelocation also needs to reference
Microsoft. Practices. Unity. dll
Microsoft. Practices. Unity. Interception. dll
The twoProgramSet. However, if you have used other application blocks, such as unity, you can simply use the logging block as the logging component.

The main concepts of logging block are as follows:

LogwriterIs an abstract class, which can be created using enterpriselibrarycontainer. Current. getinstance <logwriter>,

Enterpriselibrarycontainer is in the Microsoft. Practices. enterpriselibrary. Common. Configuration namespace,

You can also use VaR logwriter = (New logwriterfactory (). Create (); to create an object, essentially using the unity container, and using the singleton mode, no matter how many calls
Enterpriselibrarycontainer. Current. getinstance <logwriter> (); the same logwriter instance is returned.

LogfilterIs a set of configurable global filters. For example, if the enabled of log enabled filter is set to false, no logs are recorded.

Trace SourceIn the configuration fileCodeIs a classification of the log entity (logentry). A log (A logentry) can be assigned to multiple category (genearl category by default ), A category corresponds to a trace source. The reason why a trace source is called a source is relative to a trace listener, logwriter sends a logentry that is not filtered out by logfilter to one or more specified trace sources by category. The rest is the start point of the trace source, the process of sending a logentry to one or more trace listener. The trace source is a broadcast station that stores a logentry manuscript that meets the category requirements of the broadcast station sent from all over the application system, the broadcast station maintains a trace listerner list, which Copy the ogentry information to each trace listener.

Trace listenerPerform the following operations to record the logentry to the database, text files, Windows logs, and MSMQ. In the previous ent lib version, it was called the channel (sink)

Log formatterFormatting logentry outputs a set of configurable slots. One trace listener can specify zero or multiple log formatters.

In general, one trace source configuration corresponds to multiple trace listener configurations, and one trace listener configuration can be referenced by multiple trace source configurations, the same many-to-many relationship also exists between the trace listener and the log formatter configuration. Of course, the internal reference object may exist. Based on the configuration, only the trace source, tracelistener, corresponding to the number of configurations are generated, establish a reference relationship based on the configuration in the category. When the tracelistener detects that a logentry has arrived at the tracesource, it obtains the logentry and adds it to its own logentry queue, and writes it to the target storage as appropriate.

2. Windows Log and text trace listener

Event Log trace listener

To write logs to Windows logs, you must specify the source name attribute. By default, logs are written to the "application" log,

You can use system. Diagnostics. EventLog. createeventsource ("XXX System", "XXX system ");

Create an independent window log file and source log.

Refer:

Rolling flat file trace listener

Scroll flat files. Generally, text files (*. txt) are used)

Property

Description

File Name

This is the name of the rolling flat file. this is a required value. it can include environment variables such as % WINDIR %, % Temp %, and % USERPROFILE %. if you also setMax Archived FilesProperty, see the advice on choosing a file name in the followingRemarksSection.
Log File Name, which can contain environment variables such as % WINDIR % and directory paths.

Severity Filter

Applies a filter that selects the level of message that it will detect. The valid values areAll(The default ),Off,Critical,Error,Warning,Information,Verbose, AndActivitytracing. The setting interval tively means "the specified level and everything more important." For example,WarningSetting will detect warnings, errors, and critical events.

Message footer

Additional information contained in the file footer. The default is "----------------------------------------." This is optional.

Formatter name

The formatter to use with this trace listener. Select one from the drop-down list. The default is none. This is optional.
Name Reference of the formatter to be used

Message Header

Additional information contained in the file header. The default is "----------------------------------------." This is optional.

Max Archived Files

The maximum number of log files to retain. when set to an integer value, the trace listener will purge old files based on the file creation date when the number exceeds the specified value. see the note in the followingRemarksSection if you set this property.
The maximum number of log files allowed in the directory. When the number of files exceeds this limit, the files created earlier will be deleted, and the files that cannot exceed the max archived files will be deleted.[File-name] *.File-Extension

Name

This is the name of the trace listener. The default isRolling flat file trace listener. This is required.

File exists Behavior

This property determines what occurs to an existing file when it rolls over. If you selectIncrement, The Application Block creates a new file and names it by incrementing the timestamp. If you selectOverwriteAnd do not provide a value forTimestamp PatternProperty, the existing file is overwritten.
When a rolling action is triggered, whether to create a new file or overwrite the original file (after deletion, create a file with the same name)

Roll Interval

This property determines when the log file rolls over. You can selectNone(The default ),Midnight(In which case the log will roll over at midnight ),Minute,Hour,Day,Month,Week, OrYear. This is optional.
The scrolling behavior is triggered at intervals. The specific scrolling behavior is set in the file exists behavior attribute.

Roll Size KB

This is the maximum size the file can reach, in kilobytes, before it rolls over. This is optional.
The scroll action is triggered by file size. It can be used with roll interval to trigger the scroll action when multiple conditions are met.

Timestamp Pattern

This is the date/time format that is appended to the new file name (see the remarks section that follows this table ).
When creating a log file, it is used as a part of the file name. The time format string is set to yyyy-mm-dd.

Trace Output options

Trace listeners that do not output to a text formatter use this property to determine which options, or elements, shocould be encoded in the trace output. Possible values are:Callstack,Datetime,Logicaloperationstack,None,Processid,Threadid, AndTimestamp. The default isNone. For an explanation of these values, see traceoutputoptions values. This is optional.
Only when formatter name is set to null can the corresponding content of the attribute setting value be output to the log.


 
Note:
  • If the max Archived Files attribute is set, the current trace listener clears all files (the configured log storage directory) with the [file-name] *. file-Extension Rule file. Therefore, if other trace listener outputs the log file to this directory and the file name meets this rule, it will be deleted by mistake, to avoid this problem, set the file name attribute to [file-name] according to different trace listener. [Additional-name]. file-extension format.
  • You can control the triggering of file scrolling by file size, file age (creation time), or combination of two conditions (and.
  • If increment is selected as the attribute of file exists behavior, when the log file reaches the scroll point, the log application block will create a new file, the file name is the file name of the filename attribute (excluding the extension and Path) + timestamppattern + [integer +] The extension specified by the filename attribute
  • If overwrite is selected as the attribute of file exists behavior, when the log file reaches the scroll point, the application block will create a new file with the same name to replace the existing file, if you have also set the timestamp pattern attribute, the newly created file will be named by, "FILENAME attribute file name (excluding extension and Path) + timestamppattern + the extension specified by the filename attribute ". If the directory does not contain files of the same name, the file is added to the directory, if the file with the same name already exists in the directory, the application block will be deleted before creation. If the file cannot be deleted (the file may be locked), the application block will use the increment method to create a new file. In addition, when the time stamp pattern is yyyy-mm-dd, at least one log file is added every day.
  • If the filename attribute uses a relative path, the Reference Path for relative path resolution is appdomain. currentdomain. basedirectory. for example, if you set file name = "log/log.txt", the winform consoleform program creates a logfolder In the executable file directory, and the log.txt file is saved in the log folder (in the bin/debug/directory during debugging ), the aspx program will be in the root directory (with the Web. create a log folder.
3. Specific Configuration

During configuration, the xml configuration text is generated using the graphical Configuration tool provided by entlib5.0, and then copied to app. config or web. config.

1. Add reference

2. Configure web. config

<! -- Entlib5.0 Loggin -->
<Section name = "loggingconfiguration" type = "Microsoft. practices. enterpriselibrary. logging. configuration. loggingsettings, Microsoft. practices. enterpriselibrary. logging, version = 5.0.414.0, culture = neutral, publickeytoken = 31bf3856ad364e35 "requirepermission =" true "/>

3. Configure logging. config

<Loggingconfiguration name = "" tracingenabled = "true" defaultcategory = "general">
<Listeners>
<Add name = "Event Log trace listener" type = "Microsoft. practices. enterpriselibrary. logging. tracelisteners. formattedeventlogtracelistener, Microsoft. practices. enterpriselibrary. logging, version = 5.0.414.0, culture = neutral, publickeytoken = 31bf3856ad364e35"
Listenerdatatype = "Microsoft. Practices. enterpriselibrary. Logging. configuration. Libraries, Microsoft. Practices. enterpriselibrary. Logging, version = 5.0.414.0, culture = neutral, publickeytoken = token"
Source = "XXX System" formatter = "text formatter"/>
<Add name = "rolling flat file trace listener" type = "Microsoft. practices. enterpriselibrary. logging. tracelisteners. rollingflatfiletracelistener, Microsoft. practices. enterpriselibrary. logging, version = 5.0.414.0, culture = neutral, publickeytoken = 31bf3856ad364e35"
Listenerdatatype = "Microsoft. Practices. enterpriselibrary. Logging. configuration. Libraries, Microsoft. Practices. enterpriselibrary. Logging, version = 5.0.414.0, culture = neutral, publickeytoken = token"
Filename = "log/log.txt" formatter = "text formatter" rollfileexistsbehavior = "increment"
Rollsizekb = "500"/>
</Listeners>
<Formatters>
<Add type = "Microsoft. Practices. enterpriselibrary. Logging. formatters. textformatter, Microsoft. Practices. enterpriselibrary. Logging, version = 5.0.414.0, culture = neutral, publickeytoken = break"
Template = "timestamp: {timestamp} {newline} & # XA; message: {message} {newline} & # XA; Category: {category} {newline} & # XA; priority: {priority} {newline} & # XA; eventid: {eventid} {newline} & # XA; Severity: {severity} {newline} & # XA; Title: {Title} {newline} & # XA; machine: {localmachine} {newline} & # XA; app domain: {localappdomain} {newline} & # XA; processid: {localprocessid} {newline} & # XA; process name: {localprocessname} {newline} & # XA; thread name: {threadname} {newline} & # XA; Win32 threadid: {win32threadid} {newline} & # XA; extended properties: {Dictionary ({key}-{value} {newline })}"
Name = "text formatter"/>
</Formatters>
<Logfilters>
<Add type = "Microsoft. Practices. enterpriselibrary. Logging. Filters. logenabledfilter, Microsoft. Practices. Logging. Logging, version = 5.0.414.0, culture = neutral, publickeytoken = token"
Enabled = "true" name = "logging enabled filter"/>
<Add type = "Microsoft. Practices. enterpriselibrary"
Name = "Priority filter"/>
<Add type = "Microsoft. Practices. enterpriselibrary. Logging. Filters. categoryfilter, Microsoft. Practices. enterpriselibrary. Logging, version = 5.0.414.0, culture = neutral, publickeytoken = break"
Name = "category filter"/>
</Logfilters>
<Categorysources>
<Add switchvalue = "all" name = "general">
<Listeners>
<Add name = "rolling flat file trace listener"/>
</Listeners>
</Add>
<Add switchvalue = "all" name = "trace">
<Listeners>
<Add name = "rolling flat file trace listener"/>
</Listeners>
</Add>
</Categorysources>
<Specialsources>
<Allevents switchvalue = "all" name = "all events"/>
<Notprocessed switchvalue = "all" name = "unprocessed category"/>
<Errors switchvalue = "all" name = "logging errors & amp; warnings">
<Listeners>
<Add name = "Event Log trace listener"/>
</Listeners>
</Errors>
</Specialsources>
</Loggingconfiguration>

4. directory structure

============== Related code ==========================

Download

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.