Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How can we create a LOG filter for Logging purposes in C# ASP.NET WebAPI?
Action filters in C# ASP.NET Web API are used to add extra logic before or after action methods execution. The OnActionExecuting and OnActionExecuted methods allow you to inject custom logic at specific points in the request pipeline, making them perfect for logging purposes.
A LOG filter helps track API method calls, execution times, and other diagnostic information. This is particularly useful for debugging, performance monitoring, and audit trails in production applications.
Syntax
Following is the syntax for creating a custom action filter by inheriting from ActionFilterAttribute −
public class LogAttribute : ActionFilterAttribute {
public override void OnActionExecuting(HttpActionContext actionContext) {
// Logic before action execution
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) {
// Logic after action execution
}
}
Creating a Basic LOG Filter
Let us create a LogAttribute that implements ActionFilterAttribute to log information before and after action method execution −
using System;
using System.Diagnostics;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace DemoWebApplication.Controllers {
public class LogAttribute : ActionFilterAttribute {
public override void OnActionExecuting(HttpActionContext actionContext) {
Debug.WriteLine(string.Format("Action Method {0} executing at {1}",
actionContext.ActionDescriptor.ActionName,
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
"Web API Logs");
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) {
Debug.WriteLine(string.Format("Action Method {0} executed at {1}",
actionExecutedContext.ActionContext.ActionDescriptor.ActionName,
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
"Web API Logs");
}
}
}
Using the LOG Filter in Controller
Apply the custom Log attribute to your controller actions −
using System.Web.Http;
namespace DemoWebApplication.Controllers {
public class DemoController : ApiController {
[Log]
public IHttpActionResult Get() {
// Some business logic
return Ok("Data retrieved successfully");
}
[Log]
public IHttpActionResult Post([FromBody] string value) {
// Some business logic
return Ok("Data posted successfully");
}
}
}
Enhanced LOG Filter with Request Details
For more comprehensive logging, you can capture additional request information such as HTTP method, URL, and execution time −
using System;
using System.Diagnostics;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace DemoWebApplication.Controllers {
public class DetailedLogAttribute : ActionFilterAttribute {
private Stopwatch stopwatch;
public override void OnActionExecuting(HttpActionContext actionContext) {
stopwatch = Stopwatch.StartNew();
var controllerName = actionContext.ControllerContext.ControllerDescriptor.ControllerName;
var actionName = actionContext.ActionDescriptor.ActionName;
var httpMethod = actionContext.Request.Method.Method;
var requestUri = actionContext.Request.RequestUri.ToString();
Debug.WriteLine(string.Format("[{0}] Starting {1} {2}.{3} - URI: {4}",
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
httpMethod, controllerName, actionName, requestUri),
"Detailed Web API Logs");
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) {
stopwatch.Stop();
var controllerName = actionExecutedContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerName;
var actionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;
var executionTime = stopwatch.ElapsedMilliseconds;
Debug.WriteLine(string.Format("[{0}] Completed {1}.{2} - Execution Time: {3}ms",
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
controllerName, actionName, executionTime),
"Detailed Web API Logs");
}
}
}
Global LOG Filter Registration
To apply logging to all API actions globally, register the filter in WebApiConfig.cs −
using System.Web.Http;
public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
// Add global log filter
config.Filters.Add(new LogAttribute());
// Other configuration
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Output
When the LOG filter is applied, you will see output in the Debug console similar to this −
Web API Logs: Action Method Get executing at 2024-01-15 14:30:25 Web API Logs: Action Method Get executed at 2024-01-15 14:30:25 Detailed Web API Logs: [2024-01-15 14:30:25] Starting GET Demo.Get - URI: https://localhost:44300/api/demo Detailed Web API Logs: [2024-01-15 14:30:25] Completed Demo.Get - Execution Time: 15ms
Conclusion
LOG filters in ASP.NET Web API provide a clean way to implement cross-cutting concerns like logging without cluttering your business logic. By creating custom action filters, you can track API usage, measure performance, and maintain comprehensive audit logs for your applications.
