WebAPI using Exceptionfilterattribute to implement error (Exception) log records (Log4net do write library operations)

Source: Internet
Author: User
Tags log4net

WebAPI using Exceptionfilterattribute to implement error (Exception) log records (Log4net do write library operations)

Well, it's the Community app, the non-admin system, the user behavior log feeling is not very necessary, but the error log we still have to record the one. Always can not go online after the bug to make their own helpless, although there is no matter whether there is a log bug logs are a very headache.

We know that Webapi also has several filter, the previous article we do token and authority used to actionfilterattribute, this time we use Exceptionfilterattribute to do abnormal log records. First of all, our code will take the initiative to catch some exceptions manually thrown, such as the user input data validation, authorization validation, business validation and so on. There will also be some exceptions that we cannot anticipate, which could be code vulnerabilities or logical vulnerabilities ... Then we must be able to intercept all of these anomalies on a single plane, log them into the error log for analysis to use ...

Bloggers use the log4net to do log write library operation, here does not introduce the basic usage of log4net, directly on the code:

1 <log4net> 2 <!--<appender name= "Rollingfileappender" type= "log4net. Appender.rollingfileappender "> 3 <file value=" C:\testlog.txt "/> 4 <appendtofile value=" true "/&  Gt 5 <maxsizerollbackups value= "/>" 6 <maximumfilesize value= "/> 7 <rollingstyle V"       Alue= "Date"/> 8 <datepattern value= "Yyyy-mm-dd"/> 9 <staticlogfilename value= "true"/> 10 <layout type= "log4net. Layout.patternlayout "> <conversionpattern value=" Recording time:%date thread Id:[%thread] Log level:%-5level Error class:%logger prop ERTY:[%PROPERTY{NDC}]-Error description:%message%newline "/> </layout> </appender>-->
<appender name= "Adonetappender_sqlserver" type= "log4net. Appender.adonetappender "> <connectiontype value=" System.data.sqlclient.sqlconnection,system.data, Version =4.0.0.0, culture=neutral,publickeytoken=b77a5c561934e089 "/> <connectionstring value=" Data Source=.; Database=rcblog;integrated security=true; multipleactiveresultsets=true; "/> <commandtext value=" INSERT into Errorlog (logid,log_date,log_message,log _exception,log_level,logger,log_source,operatorid,operatoraccountname) VALUES (@LogId, @log_date, @LogMessage, @ Logexception, @log_level, @logger, @source, @LogOperator, @OperatorAccountName) "/> <buffersize value=" 100 "/& Gt <parameter> <parametername value= "@log_date"/> <dbtype value= "DateTime"/&G T <layout type= "log4net. Layout.rawtimestamplayout "/> </parameter> <parameter> <parametername value = "@log_level"/> <dbtype value= "String"/> <size value= ""/>, <layout type= "log4net. Layout.patternlayout "> <conversionpattern value="%level "/> </layout> + < /parameter> Notoginseng <parameter> <parametername value= "@logger"/> <dbtype value= " String "/> <size value=" 255 "/> <layout type=" log4net. Layout.patternlayout "> <conversionpattern value=%logger"/> </layout> &lt ;/parameter> <parameter> <parametername value= "@source"/> <dbtype value= "String"/> <size value= "/> <layout type=" log4net. Layout.patternlayout "> <conversionpattern value="%file:%line "/> Wuyi </layout> 52 </parameter> <!--Custom Properties--------+--<parameter>ParameterName value= "@LogId"/> <dbtype value= "String/>" <size value= "255"/> 58 <layout type= "MP. Infrastructure.systemlog.customlayout,mp. Infrastructure "> <conversionpattern value="%logid "/> </layout> </param eter> <parameter> <parametername value= "@LogException"/> <dbtype value= " String "/> <size value=" 4000 "/>-<layout type=" MP. Infrastructure.systemlog.customlayout,mp. Infrastructure "> <conversionpattern value="%logexception "/>-</layout> &lt ;/parameter> <parameter> <parametername value= "@LogMessage"/> <dbtype va Lue= "String"/> <size value= "4000"/> "<layout type=" MP. Infrastructure.systemlog.customlayout,mp. Infrastructure "> <conversionpattern value="%logmesSage "/> </layout> </parameter> <parametername Value= "@LogOperator"/> <dbtype value= "String"/> Bayi <size value= "255"/> T;layout type= "MP. Infrastructure.systemlog.customlayout,mp. Infrastructure "> <conversionpattern value="%operatorid "/> </layout>-</ parameter> <parameter> <parametername value= "@OperatorAccountName"/> <db Type value= "String"/> <size value= "255"/>-<layout type= "MP. Infrastructure.systemlog.customlayout,mp. Infrastructure "> <conversionpattern value="%operatoraccountname "/> </layout> 93 </parameter> 94 </appender> <logger name= "RCB. Logger.error "> <level value=" Error "/> <!--<appender-ref ref=" Rollingfileappender "/&GT;--> 98 <appender-ref ref= "Adonetappender_sqlserver"/> </log4net> </logger>100

Note:

The 1.<log4net> node needs to be under the <configuration> node

2. Comment out the 2-13 lines and 97 lines is the Write file

3. The value of the 23rd row indicates the cache value, the debug phase can be set to 0, in order to timely see the error log in the database

4. Bloggers Use custom attributes, by the way, the use of custom attributes, first look at the blogger's error log class:

 1//<summary> 2//System error log 3///</summary> 4 public class Errorlog 5 {6//& Lt;summary> 7///ID (GUID string) 8//</summary> 9 public string Logid {get; set;} ///&LT;SUMMARY&GT;12///Log Time//</summary>14 public DateTime log_date {g Et Set  }15//&LT;SUMMARY&GT;17///Log error messages//</summary>19 public string Log_message {get; set;} *//&LT;SUMMARY&GT;22///exception details//</summary>24 public string Log_exceptio N {get; set;} ///&LT;SUMMARY&GT;27///Error level//</summary>29 public string Log_level {ge T Set }30//&LT;SUMMARY&GT;32//Recorder (Prmms.logger)//</summary>34 public string LOGGER {get; set;} ///&LT;SUMMARY&GT;37///Log generation location///</summary>39         public string Log_source {get; set;} &LT;SUMMARY&GT;42///Operator ID43//</summary>44 public string Operatorid { Get Set }45//<summary>47//Operation account name://</summary>49 public string Operatoracco untname {get; set;}         *///&LT;SUMMARY&GT;52///ID53//</summary>54 public errorlog () 55 {. Logid = Guid.NewGuid (). ToString ("N"). ToUpper (); 57}58}

Among them, Logid, LogMessage, Operatorid, Operatoraccountname, logexception and other fields are not with the log4net, belong to the custom attribute, need to do a configuration. We create a new CustomLayout class that inherits from Patternlayout

1 Public     class Customlayout:patternlayout 2     {3 public         customlayout () 4         {5             base. Addconverter ("Logid", typeof (Logid)); 6             base. Addconverter ("LogMessage", typeof (LogMessage)); 7             base. Addconverter ("Operatorid", typeof (Operatorid)); 8             base. Addconverter ("Operatoraccountname", typeof (Operatoraccountname)); 9             base. Addconverter ("Logexception", typeof (Logexception));         }11     }

The Logid in typeof (Logid) is the one that requires our new class to inherit Patternlayoutconverter implement the Convert method.

1     internal sealed class Logid:patternlayoutconverter 2     {3         protected override void Convert (TextWriter write R, Loggingevent loggingevent) 4         {5             var content = Loggingevent.messageobject as errorlog; 6             if (content! = nul L) 7             {8                 writer. Write (content. Logid); 9             }10         }11     }

Of course, the remaining few typeof () do the same.

Log4net Write library configuration, we also need a log tool class, used to call log4net write logs, bloggers here simply wrote a few methods, the interception of 2000 length is purely personal reasons, no special significance:

 1//<summary> 2///Log Tool Class 3///</summary> 4 public class Logutils 5 {6 privat e static readonly log4net. ILog errorlog = log4net. Logmanager.getlogger ("RCB. Logger.error "); 7 8//<summary> 9 writes the specified <see cref= "Exception"/> Instance details to the error log. Ten//&LT;/SUMMARY&GT;11//<returns></returns>12 public static void Errorlog (Guid u                 Serid, String userName, Exception Exception) (Exception! = null) 15 {16 var exceptionstring = exception. ToString (); if (Exceptionstring.length >): {exceptionstr                 ing = exceptionstring.substring (0, 1999);}21 Errorlog.error (New ErrorLog22 {Operatorid = userid.tostring ("N"). ToUpper (), operatoraccountname = username,25 Log_message = excePtion.         message,26 log_exception = exceptionString27}); 28}29}30 31 &LT;SUMMARY&GT;32////writes the specified <see cref= "Exception"/> Instance details to the error log.         33//34///Record IP address///</summary>36//<returns></returns>37             public static void Errorlog (String userip, Exception Exception) (Exception = null) 40 {exceptionstring var = exception. ToString (), if (Exceptionstring.length > +), exceptionstr                 ing = exceptionstring.substring (0, 1999);}46 Errorlog.error (New ErrorLog47 {Operatorid = userip,49 Log_message = exception.         message,50 log_exception = exceptionString51}); 52}53}54 55 <summary>56////writes the specified <see cref= "Exception"/> Instance details to the error log. </summary>58///<returns></returns>59 public static void Errorlog (Except Ion exception) (Exception! = NULL) + $ var exceptionstring = ex Ception. ToString (), if (Exceptionstring.length >), {exceptionstr ing = exception. ToString ().                     Substring (0, 1999);}68 Errorlog.error (new ErrorLog69 {70 Log_message = exception. message,71 log_exception = exceptionString72}); 73}74}75}

Next, we're going to write the filter. Create a new Exceptionfilter class that inherits from Exceptionfilterattribute

 1//<summary> 2///exception Blocker 3///</summary> 4 public class Exceptionfilter:exceptionfilter Attribute 5 {6 private httpresponsemessage GetResponse (int code, string message) 7 {8 VA R Resultmodel = new Apimodelsbase () {code = code, message = message}; 9 return new Httpresponsemessage () one {Content = new Objectcontent<apimode Lsbase> (resultmodel,14 new Jsonmediatypeformatter (), 15 " Application/json "(+)};18}19 public override void Onexception (HTTPA Ctionexecutedcontext actionexecutedcontext) {$ var code = -1;23 var message = "Request failed!";  if (Actionexecutedcontext.exception is userdisplayexception) Actionexecutedcontext.exception.message;28}29 If(Actionexecutedcontext.exception is userloginexception) {= -2;32 mes Sage = actionexecutedcontext.exception.message;33}34 if (actionexecutedcontext.response = = nul             L) actionexecutedcontext.response = GetResponse (code, message); 38}39 40             Log error logs Logutils.errorlog (Securityhelper.getuserip (), actionexecutedcontext.exception); 42 43 Base. Onexception (ActionExecutedContext); 44}45}

Note:

1. The blogger individually returns the login exception through a specific code value, which facilitates client-side resolution processing

The 2.GetResponse () method is primarily populated with JSON data to response

To this step, still can't write the log, why??? Because our exceptionfilter is not yet registered, under the App_start folder WebApiConfig.cs file Register method to add the following code:

Config. Filters.add (New Exceptionfilter ());

OK, so our error log record is done. You only need to throw a manually caught exception in your code, or an unexpected uncaught exception is logged in the error log and is friendly feedback to the client.

Of course, log4net configuration information is also required to register, do not forget in the Global.asax Application_Start method plus such a code

Log4net. Config.XmlConfigurator.Configure ();

Bo Master self-knowledge level is limited, if there is not the wrong place or you have a better solution, please feel free to advise, will be humbly leave, hope to make progress together ....

Category: Web API

WebAPI using Exceptionfilterattribute to implement error (Exception) log records (Log4net do write library operations)

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.