Home > Enterprise >  How can I make my code more reusable for logging in my controllers
How can I make my code more reusable for logging in my controllers

Time:10-17

I am using same code for every controller. OnActionExecuting is called every time before action executed. how can i refactor the given code?

public class HomeController : Controller
    {

        private readonly ILogger<AccountController> logger;
        private string userId;
        private string path;

        public AccountController(
            ILogger<AccountController> logger)
        {
            this.logger = logger;
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            userId =  User.FindFirstValue(ClaimTypes.NameIdentifier) 
            path = $"{context.HttpContext.Request.Path.Value}[{context.HttpContext.Request.Method}]";
            logger.LogDebug($"{path} started. User(id): {userId}.");
        }
}

Example of how i am using it:

logger.LogInformation($"{path} Was approved for User(id)   {userId}.");

CodePudding user response:

First, create a BaseController :

public class BaseController : Controller
{

    private readonly ILogger<BaseController> logger;
    private string userId;
    private string path;

    public BaseController(IServiceProvider serviceProvider)
    {
        this.logger = serviceProvider.GetRequiredService<ILogger<BaseController>>();
    }

    public override void OnActionExecuting(ActionExecutingContext context)
    {
        userId =  User.FindFirstValue(ClaimTypes.NameIdentifier) 
        path = $"{context.HttpContext.Request.Path.Value}[{context.HttpContext.Request.Method}]";
        logger.LogDebug($"{path} started. User(id): {userId}.");
    }
}

Then, create HomeController

public class HomeController : BaseController
{
    public HomeController(IServiceProvider serviceProvider) : base(serviceProvider)
    { 
    }

}
  • Related