Log4net write to database configuration process some small issues memo

Source: Internet
Author: User
Tags reflection log4net

Issue 1: When the company makes log4net write server configuration, everything is OK, but on the home machine, this problem occurs frequently:SQL Server 2008 Error: A connection was successfully made to the server, but a failure occurred during the handshake prior to logonand this error is random, in the log4net to the database insert a few times, no problem, but the number of insertions, the frequent reported this error. Later, there was no way, the online collected a circle, and finally found the solution:After you have set the relevant TCP parameters to start, you have not experienced any problems. The problem 2,log4net is configured correctly, but it has been unable to write to the database. This problem has been plagued for a long time, finally resolved, we will look at my solution code, I also lazy to post steps. The configuration file is as follows:
 <log4net> <root> <level value= "WARN"/> <level value= "INFO"/> <level value= "D Ebug "/> <level value=" FINE "/> <!--<appender-ref ref=" Logfileappender "/>--> <append Er-ref ref= "Adonetappender"/> </root> <appender name= "Logfileappender" type= "log4net".       Appender.rollingfileappender "> <!--file name--<file value=" Log.txt "/> <!--all new logs are appended-- <appendtofile value= "true"/> <!--file name format--<datepattern value= "-yyyy. Mm.dd "/> <!--file name scrolling by date-<rollingstyle value=" date "/> <maxsizerollbackups value=" 10 "/&      Gt <!--file name is not fixed, variable--<staticlogfilename value= "false"/> <layout type= "log4net.      Layout.patternlayout "> <param name=" Conversionpattern "value="%-5p%d{yyyy-mm-dd hh:mm:ss}–%m%n "/> </layout> </appender> <appender name= "Adonetappender"Type= "Log4net.      Appender.adonetappender "> <!--buffersize is a buffer size, only log records over 1 pieces are written to the database--<buffersize value=" 1 "/> <connectiontype value= "System.Data.SqlClient.SqlConnection, System.Data, version=1.0.3300.0, Culture=neutral, publickeytoken=b77a5c561934e089 "/> <connectionstring value=" Data source=****;initial Catalog=***; Persist Security info=true; User Id=sa; password=***; Multipleactiveresultsets=true "/> <commandtext value=" INSERT into Edu_log (Date,thread,level,logger,message,        Schoolid,systypeid) VALUES (@log_date, @thread, @log_level, @logger, @content, @s_id, @t_id) "/> <parameter> <parametername value= "@log_date"/> <dbtype value= "DateTime"/> <layout type= "log4net. Layout.rawtimestamplayout "/> </parameter> <parameter> <parametername value=" @thread "/ > <dbtype value= "String"/> <size value= "255"/> <layout type= "log4net. LayOut.      Patternlayout "> <conversionpattern value="%thread "/> </layout> </parameter> <parameter> <parametername value= "@log_level"/> <dbtype value= "String"/> <si Ze value= "/> <layout type=" log4net. Layout.patternlayout "> <conversionpattern value="%level "/> </layout> &LT;/PARAMETER&G      T <parameter> <parametername value= "@logger"/> <dbtype value= "String"/> <size va lue= "255"/> <layout type= "log4net. Layout.patternlayout"> <conversionpattern value="%logger "/> </layout> </parameter> <paramet  er> <parametername value= "@content"/> <dbtype value= "String"/> <size value= "4000" /> <layout type= "FuNong.Framework.Logger.CustomLayout"> <conversionpattern value="%property{content} "/> </layout> </parameter> <parameter> <parametername value= "@s_id"/> <dbtype value= "String"/> <size valu E= "/> <layout type="FuNong.Framework.Logger.CustomLayout"> <conversionpattern value="%property{s_id} "/> </layout> </parameter> &lt ;p arameter> <parametername value= "@t_id"/> <dbtype value= "String"/> <size value= " "/> <layout type="FuNong.Framework.Logger.CustomLayout"> <conversionpattern value="%property{t_id} "/> </layout> </parameter> </ Appender> </log4net>


Note In the configuration code above:log4net. Layout.patternlayout is a configuration template provided by Log4net itself and can be used if you have a field that needs to use its own template field.

Also note this paragraph: <conversionpattern value= "%property{s_id}"/> it shows that we will use the existing property escape template provided by log4net to identify our fields.

But if you have custom fields, you need to write layout and converter yourself. In the above configuration file, content,s_id,t_id is my custom three fields, how to let these three fields also write to the database, we step by step to configure.

First, you need to put three custom fields into an entity class:

namespace funong.framework.logger{public    class logcontent    {public        logcontent (string content, String S_ ID, string t_id)        {            this.content = content;            this.s_id = s_id;            this.t_id = t_id;        }        public string content {get; set;}        public string s_id {get; set;}        public string t_id {get; set;}}    }

Then, we define our own layout, because we use the property field template, so we need to add it in the following way:

namespace funong.framework.logger{public    class Customlayout:patternlayout    {public        customlayout ()        {this            . Addconverter ("Property", typeof (Xpatternconverter));}}    

In the end, our converter has achieved:

Namespace funong.framework.logger{public class Xpatternconverter:patternlayoutconverter {protected Overri de void Convert (System.IO.TextWriter writer, log4net. Core.loggingevent loggingevent) {if (this. Option! = null) {//Write the value for the specified key writeobject (writer, lo            Ggingevent.repository, Lookupproperty (Option, loggingevent)); } else {//Write all the key value pairs writedictionary (writer, Logg            Ingevent.repository, Loggingevent.getproperties ()); }}///<summary>///To get the value of an attribute of an incoming log object by reflection///</summary>//<param Nam E= "Property" ></param>///<returns></returns> private Object lookupproperty (String prop Erty, Log4net.            Core.loggingevent loggingevent) {Object propertyvalue = String.Empty; PropertyInfo PropertyInfo;            PropertyInfo = LoggingEvent.MessageObject.GetType ().            GetProperty (property); if (propertyInfo! = null) {PropertyValue = Propertyinfo.getvalue (Loggingevent.messageobject, Nu            ll);        } return propertyvalue; }    }}

From the above code, we can see that log4net will recognize the fields in this entity by reflection, and then assign the values to the database logcontent.

Here's a little bit of packing:

Namespace funong.framework.logger{public    interface Iloggerservice    {        void Debug (Object message);        void Error (Object message);        void Fatal (Object message);        void Info (Object message);        void Warn (Object message);}    }

namespace funong.framework.logger{public    class Loggerservice:iloggerservice    {public        loggerservice ()        {            log4net. Config.XmlConfigurator.Configure ();            Logger = Logmanager.getlogger (typeof (Loggerservice));        }        Private readonly ILog logger;        public void Info (object message)        {            logger. Info (message);        }        public void Warn (object message)        {            logger. Warn (message);        }        public void Debug (object message)        {            logger. Debug (message);        }        public void Error (object message)        {            logger. Error (message);        }        public void Fatal (object message)        {            logger. Fatal (message);}}}           

Since I used AUTOFAC as an IOC, let's just look at how we use it:

  protected override void Onauthorization (AuthorizationContext filtercontext)        {            if (auth)            {                var Collection = Cookie. Getcookiecollection ("FuNong.UserInfo.Login");                if (collection = = null)                {                    logger. Warn (New logcontent ("User login information extraction failed, will jump to the landing screen ...", "1", "2"));                    Filtercontext.result = new Redirectresult ("Home/login");                }                else                {                    logger. Info (New logcontent ("User verified successfully, continue before operation ...", "1", "2"));}}}        

So, when we run, we find that the program has already written the data to the database.

The entire configuration is not difficult, but there are a lot of details, slightly careless, which could result in a database not being written to.

Log4net write to database configuration process some small issues memo

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.