Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use ActionFilterAttribute to record API logs

Shulou Source: shulou.com Published: 2022-06-03 04:08:52 09月18日 Update

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!

Tags: Result log content method actual method controller parameter address character string sequence data time project learning practical deeper code Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Docker Microsoft MariaDB MySQL