WEBAPI Service Monitoring

Source: Internet
Author: User
Tags get ip servervariables

This article mainly describes when to request Webapi, monitor the time the action executes, and the parameter values that the action passes, as well as the HTTP request header information. Using log4net to record the monitoring log, the time of logging is convenient for us to locate which action takes too long to execute, and then take the optimization method.

Metrics for monitoring log monitoring such as

Monitoring program Implementation

The monitor program mainly inherits the ActionFilterAttribute class, in the namespace: System.Web.Http.Filters, overrides the OnActionExecuted (httpactionexecutedcontext ActionExecutedContext) and onactionexecuting (Httpactioncontext Actioncontext) two methods. in the previous article, the monitoring of MVC was also overridden by the ActionFilterAttribute class, but MVC's ActionFilterAttribute under the System.Web.Mvc namespace .

1. Monitoring Log objects
/// <summary>    ///Monitoring Log Objects/// </summary>     Public classWebapimonitorlog { Public stringControllername {Get; Set; }         Public stringActionName {Get; Set; }         PublicDateTime Executestarttime {Get; Set; }         PublicDateTime Executeendtime {Get; Set; }        /// <summary>        ///the requested action parameter/// </summary>         Publicdictionary<string,Object>Actionparams {Get; Set; }        /// <summary>        ///HTTP request Header/// </summary>         Public stringHttprequestheaders {Get; Set; }        /// <summary>        ///Request Method/// </summary>         Public stringHttpMethod {Get; Set; }        /// <summary>        ///the requested IP address/// </summary>         Public stringIP {Get; Set; }        /// <summary>        ///Get monitoring metrics log/// </summary>        /// <param name= "Mtype" ></param>        /// <returns></returns>         Public stringGetloginfo () {stringMSG =@"Action Execution Time monitoring: Controllername:{0}controller actionname:{1} start time: {2} End time: {3} Total time: {4} Second action parameter: {5} HTTP request header: {6} Client ip:{7}, HTTPME THOD:{8}"; return string. Format (MSG, Controllername, ActionName, Executestarttime, Exec Uteendtime, (Executeendtime-executestarttime).                TotalSeconds, Getcollections (actionparams), Httprequestheaders, IP,        HttpMethod); }        /// <summary>        ///get the Action parameter/// </summary>        /// <param Name= "Collections" ></param>        /// <returns></returns>         Public stringGetcollections (dictionary<string,Object>collections) {            stringParameters =string.            Empty; if(Collections = =NULL|| Collections.count = =0)            {                returnParameters; }            foreach(stringKeyinchcollections.keys) {Parameters+=string. Format ("{0}={1}&", Key, Collections[key]); }            if(!string. Isnullorwhitespace (Parameters) && Parameters.endswith ("&") ) {Parameters= Parameters.substring (0, Parameters.length-1); }            returnParameters; }        /// <summary>        ///Get IP/// </summary>        /// <returns></returns>         Public stringGetIP () {stringIP =string.            Empty; if(!string. IsNullOrEmpty (system.web.httpcontext.current.request.servervariables["Http_via"])) IP= Convert.ToString (system.web.httpcontext.current.request.servervariables["http_x_forwarded_for"]); if(string. IsNullOrEmpty (IP)) IP= Convert.ToString (system.web.httpcontext.current.request.servervariables["REMOTE_ADDR"]); returnIP; }    }
2. Monitoring procedures
[AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, AllowMultiple =false)]     Public classWebapitrackerattribute:actionfilterattribute//, Exceptionfilterattribute    {        Private ReadOnly stringKey ="_thiswebapionactionmonitorlog_";  Public Override voidonactionexecuting (Httpactioncontext actioncontext) {Base.            OnActionExecuting (Actioncontext); Webapimonitorlog Monlog=NewWebapimonitorlog (); Monlog.executestarttime=DateTime.Now; //get the Action parameterMonlog.actionparams =actioncontext.actionarguments; Monlog.httprequestheaders=actionContext.Request.Headers.ToString (); Monlog.httpmethod=ActionContext.Request.Method.Method; Actioncontext.request.properties[key]=Monlog; varform=System.Web.HttpContext.Current.Request.Form; #regionIf the parameter is an entity object, gets the serialized dataStream Stream=ActionContext.Request.Content.ReadAsStreamAsync ().            Result; Encoding Encoding=Encoding.UTF8; Stream. Position=0; stringResponseData =""; using(StreamReader reader =NewStreamReader (stream, encoding)) {ResponseData=Reader. ReadToEnd ().            ToString (); }            if(!string. Isnullorwhitespace (responsedata) &&! MonLog.ActionParams.ContainsKey ("__entityparamslist__") ) {monlog.actionparams["__entityparamslist__"] =ResponseData; }            #endregion        }         Public Override voidonactionexecuted (Httpactionexecutedcontext actionexecutedcontext) {webapimonitorlog MonLog= Actionexecutedcontext.request.properties[key] asWebapimonitorlog; Monlog.executeendtime=DateTime.Now; Monlog.actionname=ActionExecutedContext.ActionContext.ActionDescriptor.ActionName; Monlog.controllername=ActionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName;            Log.info (Monlog.getloginfo ()); if(Actionexecutedcontext.exception! =NULL)            {                stringMSG =string. Format (@"request ' {1} ' of ' {0}controller ' to produce an exception: Action parameter: {2} HTTP request header: {3} client I P:{4}, httpmethod:{5}", Monlog.controllername, Monlog.actionname, Monlog.getcollections (Monlog.actionparams),                Monlog.httprequestheaders, Monlog.getip (), Monlog.httpmethod);            Log.error (MSG, actionexecutedcontext.exception); }        }    }
3. Reference monitoring

We can monitor the Webapicontroller or action directly by referencing [Webapitracker] on each Webapicontroller class or action.

We can also register global monitoring in Global.asax so that we can monitor the action in each Webapicontroller, the code is as follows:

protected void Application_Start ()        {                        GlobalConfiguration.Configuration.Filters.Add (new  Webapitrackerattribute ());            Arearegistration.registerallareas ();        }
Loggerhelper refer to the following article

MVC Monitoring: http://www.cnblogs.com/lc-chenlong/p/4228639.html

WEBAPI Service Monitoring

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.