Use log4net to record logs in projects

Source: Internet
Author: User
I. Preparations
  1. A copy of the log4net source code or a generated log4net. dll file
  2. Create a new table in the database.
  3. Configuration file.
  4. Method for logging.
Ii. Start-log4net. dll

Log4net Official Website: http://logging.apache.org/log4net/

Click here to download the compiled log4net. dll file!

Add a reference to log4net. DLL to the project.

3. Create a table

-- Create a database table

Createtable [DBO]. [logcenter] (

[ID] [int] Primary Key Identity (1, 1) not null,

[Date] [datetime] notnull,

[Thread] [varchar] (255) not null,

[Level] [varchar] (50) not null,

[Logger] [varchar] (255) not null,

[Message] [varchar] (4000) not null,

[Exception] [varchar] (2000) null

)

4. Add a configuration file
<? XML version = "1.0" encoding = "UTF-8"?> <Configuration> <! -- This configuration must be placed under configuration --> <configsections> <section name = "log4net" type = "log4net. config. log4netconfigurationsectionhandler, log4net"/> </configsections> <! -- Log4net configuration node --> <log4net> <logger name = "loginfo"> <level value = "info"/> <appender-ref = "adonetappender_sqlserver"/> <appender- ref ref = "infoappender"/> </logger> <! -- <Root> <level value = "all"/> <appender-ref = "adonetappender_sqlserver"/> <appender-ref = "infoappender"/> </root> --> <appender name = "infoappender" type = "log4net. appender. rollingfileappender "> <Param name =" file "value =" log \ info \ "/> <Param name =" appendtofile "value =" true "/> <Param name = "maxfilesize" value = "10240"/> <Param name = "maxsizerollbackups" value = "100"/> <Param name = "staticlogfil Ename "value =" false "/> <Param name =" datepattern "value =" yyyymmdd&quot;.txt & quot; "/> <Param name =" rollingstyle "value =" date "/> <layout type =" log4net. layout. patternlayout "> <Param name =" conversionpattern "value =" log time: % d message: % m exception: % exception % newline "/> </layout> </appender> <appender name =" adonetappender_sqlserver "type =" log4net. appender. adonetappender "> <! -- Buffersize indicates the buffer size. Only five logs are written to the database. --> <buffersize value = "0"/> <! -- 2.0 this is the corresponding sql2008 if it is 2000 or 2005 another configuration --> <connectiontype value = "system. data. sqlclient. sqlconnection, system. data, version = 2.0.0.0, culture = neutral, publickeytoken = b77a5c561934e089 "/> <! -- Connect to the database string ADO. net Type connection --> <connectionstring value = "Data Source = SHOPEX-SH-A0449 \ fanyong; initial catalog = onlineshop; user id = sa; Password = sa;"/> <! -- Insert to table log --> <commandtext value = "insert into logcenter ([date], [thread], [level], [logger], [Message], [Exception]) values (@ log_date, @ thread, @ log_level, @ logger, @ message, @ exception) "/> <parameter> <parametername value =" @ log_date "/> <dbtype value =" datetime "/> <layout type =" log4net. layout. patternlayout "> <conversionpattern value =" % Date {yyyy '-'mm'-'dd hh': 'mm': 'ss '. 'fff} "/> </layout> <! -- <Layout type = "log4net. layout. rawtimestamplayout "/> --> </parameter> <parametername value =" @ thread "/> <dbtype value =" string "/> <size value =" 255 "/> <! -- Logcomponent is the namespace where the class is located, and mylayout is the class where the custom attribute is located. This is the part we want to write. It will be introduced below. --> <Layout type = "log4net. layout. patternlayout "> <conversionpattern value =" % thread "/> </layout> </parameter> <parametername value =" @ log_level "/> <dbtype value =" String "/> <size value =" 50 "/> <layout type =" log4net. layout. patternlayout "> <conversionpattern value =" % level "/> </layout> </parameter> <parametername value =" @ logger "/> <dbtype value =" String & quot;/> <size value = "255"/> <layout type = "log4net. layout. patternlayout "> <conversionpattern value =" % logger "/> </layout> </parameter> <parametername value =" @ message "/> <dbtype value =" String & quot;/> <size value = "4000"/> <layout type = "log4net. layout. patternlayout "> <conversionpattern value =" % message "/> </layout> </parameter> <parametername value =" @ exception "/> <dbtype value =" String & quot;/> <size value = "2000"/> <layout type = "log4net. layout. predictionlayout "/> </parameter> </appender> </log4net> </configuration>
5. Implementation Code for logging

Implementation:

Using system;

Namespace log4nettet

{

/// <Summary>

/// Log operation class

/// </Summary>

Public class logwrite

{

Private logwrite ()

{

// Configuration file of the constructor settings

Setconfig ();

}

// Create a log4net object

//

Private Static readonly log4net. ilog loginfo = log4net. logmanager. getlogger ("loginfo ");

Private Static bool isloadconfig = false;

// Set the configuration file

//

Private Static void setconfig ()

{

Log4net. config. xmlconfigurator. Configure ();

}

/// <Summary>

/// Record exception information

/// </Summary>

/// <Param name = "info"> error message </param>

Public static void writelog (string info)

{

If (! Isloadconfig)

{

Setconfig ();

Isloadconfig = true;

}

If (loginfo. isinfoenabled)

{

Loginfo. Info (Info );

}

}

Public static void writelog (string info, exception ex)

{

If (! Isloadconfig)

{

Setconfig ();

Isloadconfig = true;

}

If (loginfo. iserrorenabled)

{

Loginfo. Error (Info, ex );

}

}

}

}

6. Test code

Because the implementation code of the logwrite class is a static method, you do not need to instantiate it when calling it. You can simply call it.

 

Protected void btnlog4net_click (Object sender, eventargs e) {// common Log message
Log4nettest. logwrite. writelog ("Test message ");
// Exception information
Log4nettest. logwrite. writelog ("an exception is reported", new exception ("this is an exception message "));

        }
 
VII. Final Results

 

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.