In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on "how to use ActionFilterAttribute to achieve API log recording", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use ActionFilterAttribute to record API logs.
Mode of realization
1. First, when entering action, define OnActionExecuting.
Public override void OnActionExecuting (ActionExecutingContext context) {base.OnActionExecuting (context); / / the request body of the acquisition request has been added later. If you don't need to delete it in the actual project, you can long contentLen = context.HttpContext.Request.ContentLength = = null? 0: context.HttpContext.Request.ContentLength.Value If (contentLen > 0) {/ / read everything in the request body System.IO.Stream stream = context.HttpContext.Request.Body; if (context.HttpContext.Request.Method = = "POST") {stream.Position = 0 } byte [] buffer = new byte [contentLen]; stream.Read (buffer, 0, buffer.Length); / / convert to the string RequestBody = System.Text.Encoding.UTF8.GetString (buffer);} ActionArguments = Newtonsoft.Json.JsonConvert.SerializeObject (context.ActionArguments) Stopwatch = new Stopwatch (); Stopwatch.Start ();}
2. Define Stopwatch and calculate the time consuming of the method.
Private string ActionArguments {get; set;} / all values in the request body / private string RequestBody {get; set;} private Stopwatch Stopwatch {get; set;}
3. At the end, print the information out to OnActionExecuted.
Public override void OnActionExecuted (ActionExecutedContext context) {base.OnActionExecuted (context); Stopwatch.Stop (); string url = context.HttpContext.Request.Host + context.HttpContext.Request.Path + context.HttpContext.Request.QueryString; string method = context.HttpContext.Request.Method; string controller = context.Controller.ToString (); string action = context.ActionDescriptor.DisplayName String token = "; if (context.HttpContext.Request! = null & & context.HttpContext.Request.Headers! = null & & context.HttpContext.Request.Headers [" Authorization "] .Count > 0) {token = context.HttpContext.Request.Headers [" Authorization "];} string qs = ActionArguments Dynamic result = context?.Result?.GetType ()?. Name = = "EmptyResult"? New {Value = "No result returned"}: context?.Result as dynamic; string res = "exception occurred before returning result"; try {if (result! = null) {res = Newtonsoft.Json.JsonConvert.SerializeObject (result.Value) }} catch (System.Exception) {res = "the log did not get the result, and the returned data cannot be serialized" } NLogger.Info ($"address: {url}\ n" + $"controller: {controller}\ n" + $"action: {action}\ n" + $"token: {token}\ n" + $"method: { Method}\ n "+ $" request body: {RequestBody}\ n "+ $" Parameter: {qs}\ n "+ $" result: {res}\ n "+ $" time: {Stopwatch.Elapsed.TotalMilliseconds} milliseconds (refers to the time the corresponding method is executed within the controller) }
4. The controller calls LogAttribute.
/ / [Produces ("application/json")] [LogAttribute] [CustomExceptionFilterAttribute] public class DefaultController: Controller {}
Complete code
Using CompanyName.ProjectName.Core; using Microsoft.AspNetCore.Mvc.Filters; using System.Diagnostics; namespace CompanyName.ProjectName.HttpApi.Host.Code {/ interceptor / public class LogAttribute: ActionFilterAttribute {private string ActionArguments {get; set;} / all values in the request body / private string RequestBody {get; set } private Stopwatch Stopwatch {get; set;} / public override void OnActionExecuting (ActionExecutingContext context) {base.OnActionExecuting (context) / / the request body of the acquisition request has been added later. If you don't need to delete it in the actual project, you can long contentLen = context.HttpContext.Request.ContentLength = = null? 0: context.HttpContext.Request.ContentLength.Value If (contentLen > 0) {/ / read everything in the request body System.IO.Stream stream = context.HttpContext.Request.Body; if (context.HttpContext.Request.Method = = "POST") {stream.Position = 0 } byte [] buffer = new byte [contentLen]; stream.Read (buffer, 0, buffer.Length); / / convert to the string RequestBody = System.Text.Encoding.UTF8.GetString (buffer);} ActionArguments = Newtonsoft.Json.JsonConvert.SerializeObject (context.ActionArguments) Stopwatch = new Stopwatch (); Stopwatch.Start ();} / public override void OnActionExecuted (ActionExecutedContext context) {base.OnActionExecuted (context); Stopwatch.Stop () String url = context.HttpContext.Request.Host + context.HttpContext.Request.Path + context.HttpContext.Request.QueryString; string method = context.HttpContext.Request.Method; string controller = context.Controller.ToString (); string action = context.ActionDescriptor.DisplayName; string token = "" If (context.HttpContext.Request! = null & & context.HttpContext.Request.Headers! = null & & context.HttpContext.Request.Headers ["Authorization"] .Count > 0) {token = context.HttpContext.Request.Headers ["Authorization"];} string qs = ActionArguments; dynamic result = context?.Result?.GetType ()? .name = = "EmptyResult"? New {Value = "No result returned"}: context?.Result as dynamic; string res = "exception occurred before returning result"; try {if (result! = null) {res = Newtonsoft.Json.JsonConvert.SerializeObject (result.Value) }} catch (System.Exception) {res = "the log did not get the result, and the returned data cannot be serialized" } NLogger.Info ($"address: {url}\ n" + $"controller: {controller}\ n" + $"action: {action}\ n" + $"token: {token}\ n" + $"method: { Method}\ n "+ $" request body: {RequestBody}\ n "+ $" Parameter: {qs}\ n "+ $" result: {res}\ n "+ $" time: {Stopwatch.Elapsed.TotalMilliseconds} milliseconds (refers to the time the corresponding method is executed within the controller) } at this point, I believe you have a deeper understanding of "how to use ActionFilterAttribute to record API logs". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.