Use func delegates to record API logs

Time:2021-7-24

problem

When we develop web APIs, we usually need to record the input and output information of the API to facilitate subsequent troubleshooting; So what do we usually do? We usually write a public method to control input and output in a public place. This is funcCommission comes in handy.

What is func

FuncEncapsulates a method that has one parameter and returns the type value specified by the tresult parameter. Using funcA delegate represents a method that can be passed as a parameter without explicitly declaring a custom delegate.   The encapsulated method must correspond to the method signature defined by this delegate.   That is, the encapsulated method must have a parameter passed to it by value and must return a value. Using funcWhen delegating, it is not necessary to explicitly define a delegate that encapsulates a method with only one parameter.

Main code implementation

1. Define delegates.

private ApiResult HandleWork(CreateBQoolSyncEventModel syncModel, Func work)
        {
            //Record DB event first
            _innerBQoolSyncEventLogService.Create(syncModel);

            var result = new ApiResult();
            try
            {
                _logger.Info($"Call Web Api Start, data:{syncModel.ToJsonString()}");
                result = work();
                if (!result.Success && !string.IsNullOrEmpty(result.Code) && string.IsNullOrEmpty(result.ErrorMessage))
                {
                    result.ErrorMessage = ApiResultCode.ErrorMessages[result.Code];
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex.ToString());
                result.Success = false;
                if (string.IsNullOrEmpty(result.ErrorMessage))
                {
                    result.ErrorMessage = ex.Message;
                }
                else
                {
                    result.ErrorMessage += "; " + ex.Message;
                }
            }
            finally
            {
                _logger.Info($"Call Web Api End , result:{result.ToJsonString()}");

                //Update DB event
                syncModel.SetStatus(result.Success ? BQoolSyncEventStatus.Success : BQoolSyncEventStatus.Failure);
                _innerBQoolSyncEventLogService.ChangeStatus(syncModel.Id, syncModel.Status, result.ErrorMessage);
            }

            return result;
        }

2. Pass the method as a parameter into the delegate.

[HttpPost]
        public ApiResult ModuleFeatureSetting(ReviewsApiRequestModel model)
        {
            string data = StringTools.AESDecrypt(model.Encrypt);
            var param = JObject.Parse(data).ToObject();

            ApiResult result = HandleWork(
                new CreateBQoolSyncEventModel(param.Account, BQoolSyncEventType.ModuleFeatureSetting, param)
                , () => _ReviewsSettingSyncService.ModuleFeatureSetting(param));

            return result;
        }

3. View the log.