Log4net adding custom logs to the database

Source: Internet
Author: User
Tags log4net

Example of adding an operation log to a database:

(a) Create a database of Operation log table, as follows I built a simple log table

(b) The configuration file is configured as follows

  <log4net>  <!--Error Logging Database -    <Loggername= "Operatedb">      < Levelvalue= "INFO"/>      <Appender-refref= "Adonetappender_opertosql" />    </Logger><!--operation log Logging to database -    <Appendername= "Adonetappender_opertosql"type= "log4net." Appender.adonetappender ">      <ConnectionTypevalue= "System.Data.SqlClient.SqlConnection, System.Data, version=1.0.5000.0, Culture=neutral, publickeytoken= b77a5c561934e089 " />      <connectionStringvalue= "server=192.168.1.188\mssqlserver2008;database=hotelmis;uid=sa;pwd=123456;" />      <CommandTextvalue= "INSERT into Operatelog (LogLevel, MSG, ClassName, Method, Cby, Cdt) VALUES (@LogLevel, @Msg, @ClassName, @Method, @Cby , @Cdt) " />      <buffersizevalue= "1" />      <parameter>        <parameternamevalue= "@LogLevel" />        <DbTypevalue= "String" />        <sizevalue= " +" />        <Layouttype= "log4net." Layout.patternlayout "value= "%level" />      </parameter>            <parameter>        <parameternamevalue= "@Msg" />        <DbTypevalue= "String" />        <sizevalue= "10240" />        <Layouttype= "Util.myloglayout, Util">          <Conversionpatternvalue= "%property{msg}" />        </Layout>      </parameter>      <parameter>        <parameternamevalue= "@ClassName" />        <DbTypevalue= "String" />        <sizevalue= " the" />        <Layouttype= "Util.myloglayout, Util" >          <paramname= "Conversionpattern"value= "%property{classname}"/>        </Layout>      </parameter>      <parameter>        <parameternamevalue= "@Method" />        <DbTypevalue= "String" />        <sizevalue= " the" />        <Layouttype= "Util.myloglayout, Util" >          <paramname= "Conversionpattern"value= "%property{method}"/>        </Layout>      </parameter>      <parameter>        <parameternamevalue= "@Cby" />        <DbTypevalue= "String" />        <sizevalue= " +" />        <Layouttype= "Util.myloglayout, Util" >          <paramname= "Conversionpattern"value= "%property{cby}"/>        </Layout>      </parameter>            <parameter>        <parameternamevalue= "@Cdt" />        <DbTypevalue= "DateTime" />        <Layouttype= "log4net." Layout.rawtimestamplayout " />      </parameter>    </Appender>  </log4net>

(iii) Define your own layout and Mymessagepatternconverter classes

namespace util{    publicclass  myloglayout:patternlayout      {        public myloglayout ()          {              this. Addconverter ("Property"typeof(Mymessagepatternconverter));          }      }

namespaceutil{ Public classMymessagepatternconverter:patternlayoutconverter {protected Override voidConvert (System.IO.TextWriter writer, log4net. Core.loggingevent loggingevent) {if(Option! =NULL)            {                //Write The value for the specified keyWriteObject (writer, loggingevent.repository, Lookupproperty (Option, loggingevent)); }            Else            {                //Write all the key value pairsWritedictionary (writer, loggingevent.repository, Loggingevent.getproperties ()); }          }        /// <summary>          ///To get the value of an attribute of an incoming log object by reflection/// </summary>          /// <param name= "property" ></param>          /// <returns></returns>          Private ObjectLookupproperty (stringProperty , Log4net. Core.loggingevent loggingevent) {ObjectPropertyValue =string.            Empty; PropertyInfo PropertyInfo=LoggingEvent.MessageObject.GetType ().            GetProperty (property); if(PropertyInfo! =NULL) PropertyValue= Propertyinfo.getvalue (Loggingevent.messageobject,NULL); returnPropertyValue; }      }}

(iv) Finally can be called, I wrote here a public class log

[Assembly:log4net. Config.xmlconfigurator (Watch = False)]
Namespaceutil{ Public classLog {#regionLogging the operation log to the database/// <summary> ///logging the operation log to the database/// </summary> /// <param name= "user" ></param> /// <param name= "msg" ></param> /// <param name= "ClassName" ></param> /// <param name= "method" ></param> Public Static voidOperatedb (stringUserstringMsgstringClassName,stringmethod) {ILog Logger= Logmanager.getlogger ("Operatedb"); Logger. Info (NewLogcontent () {msg = msg, Cby = user, ClassName = ClassName, method = method});//writes exception information to disk. } /// <summary> ///logging the operation log to the database/// </summary> /// <param name= "user" ></param> /// <param name= "msg" ></param> Public Static voidOperatedb (stringUserstringmsg) {ILog Logger= Logmanager.getlogger ("Operatedb"); Logger. Info (NewLogcontent () {msg = msg, Cby = user, ClassName =NULL, Method =NULL});//writes exception information to disk. } #endregion }}

Log4net adding custom logs to the database

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.