ConcurrentQueue对列的基本使用方式

  队列(Queue)代表了一个先进先出的对象集合。当您需要对各项进行先进先出的访问时,则使用队列。当您在列表中添加一项,称为入队,当您从列表中移除一项时,称为出队

  ConcurrentQueue<T>队列是一个高效的线程安全的队列,是.Net Framework 4.0,System.Collections.Concurrent命名空间下的一个数据结构。

 1 对列初始化:
 2 
 3 ConcurrentQueue<ApiLogContract> Queue = new ConcurrentQueue<ApiLogContract>();
 4 
 5 /// <summary>
 6 /// 单条入队列
 7 /// </summary>
 8 /// <param name="model">入列模型</param>
 9 
10 Queue.Enqueue(model);
11 
12 
13 
14 /// <summary>
15 /// 多条入队
16 /// </summary>
17 /// <param name="list"></param>
18 
19 List<ApiLogContract> list = new List<ApiLogContract>();
20 
21 list.add(new model{});
22 
23 list.add(new model{});
24 
25 list.add(new model{});
26 
27 list.add(new model{});
28 
29 list.ForEach(t => Enqueue(t));
30 
31 
32 
33 /// <summary>
34 /// 单条出队
35 /// </summary>
36 /// <returns></returns>
37 
38 ApiLogContract apiLog = null;
39 Queue.TryDequeue(out apiLog);
40 
41 
42 
43 /// <summary>
44 /// 多条出队
45 /// </summary>
46 /// <param name="count">数量</param>
47 /// <returns></returns>
48 
49 var logs = new List<ApiLogContract>();
50 
51 if (Queue.Count > 0)
52 {
53   for (int i = 0; i < count; i++)
54   {
55     var source = Dequeue();
56     if (source != null)
57     {
58       logs.Add(source);
59     }
60   }
61 }
/// <summary>
/// 获取对列数量
/// </summary>
/// <returns></returns>
Queue.Count

/// <summary>
/// 确定序列是否包含任何元素[用于判断对列是否有要处理的数据]这个方法的性能比Count()方法快
/// </summary>
/// <returns></returns>
Queue.Any()

以上就是对列的基本使用方法。

对列的使用场景有很多。所有要异步处理的都可以使用对列的方式。如接口日志异步处理,邮件、短信异步发送等。对列一般配合单例设计模式和线程一起使用更佳。

示例:

接口日志异步写入。不影响接口性能。

/// <summary>
    /// 接口日志对列
    /// </summary>
    public sealed class ApiLogQueueService
    {
        #region 属性成员

        /// <summary>
        /// 单例
        /// </summary>
        private static ApiLogQueueService _Instance = new ApiLogQueueService();

        /// <summary>
        /// 上次写入时间
        /// </summary>
        public DateTime LastWriteTime = DateTime.Now;

        /// <summary>
        /// 是否写入运行线程日志
        /// </summary>
        public bool IsWriteInitLog = false;

        /// <summary>
        /// 是否刷新缓存
        /// </summary>
        public bool IsRefreshCache = false;

        /// <summary>
        /// 上次刷新时间
        /// </summary>
        public DateTime LastRefreshTime = DateTime.Now;

        /// <summary>
        /// 是否写入监控线程日志
        /// </summary>
        public bool IsWriteMonitorLog = false;

        /// <summary>
        /// 接口日志服务类对象
        /// </summary>
        private IApiLogService logsService = ServiceFactory.ApiLogs;

        /// <summary>
        /// 队列
        /// </summary>
        private static readonly ConcurrentQueue<ApiLogServiceModel> Queue = new ConcurrentQueue<ApiLogServiceModel>();

        #endregion

        /// <summary>
        /// 私有默认构造
        /// </summary>
        private ApiLogQueueService()
        {
            Init();
            InitMonitoring();
        }

        /// <summary>
        /// 单例只读属性
        /// </summary>
        public static ApiLogQueueService Instance
        {
            get
            {
                return _Instance;
            }
        }

        #region 操作对列方法
        /// <summary>
        /// 单条入队列
        /// </summary>
        /// <param name="model">入列模型</param>
        public void Enqueue(ApiLogServiceModel model)
        {
            //判断是否使用日志对列
            if (Queue.Count < SystemConst.Queue.ApiLogQueueMaxCount)// && ServiceFactory.DictionaryItem.QueueIsOn()
            {
                Queue.Enqueue(model);
            }
            else
            {
                //string responseData = model.ResponseModel != null ? model.ResponseModel string.Empty;
                //if (string.IsNullOrEmpty(responseData) && model.ResponseModel != null)
                //{
                //    responseData = JsonConvert.SerializeObject(model.ResponseModel);
                //}
                //logsService.AddLog(model.LogTypeEnum, model.ProjectId, model.InterfaceNameEnum, model.RequestData, responseData, model.SearchText1, model.SearchText2, model.ElapsedTime, model.CreatedBy, model.Remark);
            }
        }

        /// <summary>
        /// 多条入队
        /// </summary>
        /// <param name="list"></param>
        public void Enqueue(List<ApiLogServiceModel> list)
        {
            list.ForEach(t => Enqueue(t));
        }

        /// <summary>
        /// 单条出队
        /// </summary>
        /// <returns></returns>
        public ApiLogServiceModel Dequeue()
        {
            ApiLogServiceModel apiLog;
            Queue.TryDequeue(out apiLog);
            return apiLog;
        }

        /// <summary>
        /// 多条出队
        /// </summary>
        /// <param name="count">数量</param>
        /// <returns></returns>
        public List<ApiLog> Dequeue(int count)
        {
            var logs = new List<ApiLog>();

            if (Queue.Count > 0)
            {
                for (int i = 0; i < count; i++)
                {
                    var source = Dequeue();
                    if (source != null)
                    {
                        var model = new ApiLog()
                        {
                            Search1 = string.IsNullOrEmpty(source.Search1) ? string.Empty : source.Search1,
                            Search2 = string.IsNullOrEmpty(source.Search2) ? string.Empty : source.Search2,
                            ClassName = source.ClassName.SubstringExtend(100),
                            Method = source.Method.SubstringExtend(100),
                            Type = source.Type,
                            ProjectId = source.ProjectId,
                            Code = source.Code,
                            RequestData = source.RequestModel != null ? JsonConvert.SerializeObject(source.RequestModel) : source.RequestData,
                            ResponseData = source.ResponseModel != null ? JsonConvert.SerializeObject(source.ResponseModel) : source.ResponseData,
                            ResultCode = source.ResultCode,
                            ElapsedTime = source.ElapsedTime,
                            ExecuteStartTime = source.ExecuteStartTime,
                            ExecuteEndTime = source.ExecuteEndTime,
                            TimeDifference = source.TimeDifference,
                            Remark = source.Remark,
                            RowStatus = TrueOrFalseEnum.True.GetHashCode(),
                            CreatedBy = source.CreatedBy,
                            CreatedOn = DateTime.Now,
                            UpdatedBy = source.UpdatedBy,//source.UpdatedBy CommonHelp.ServiceIp
                            UpdatedOn = SystemConst.DateTimeDefault
                        };
                        model.Search1 = source.Search1.SubstringExtend(100);
                        model.Search2 = model.Search2.SubstringExtend(100);
                        logs.Add(model);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            return logs;
        }

        /// <summary>
        /// 获取对列数量
        /// </summary>
        /// <returns></returns>
        public int GetCount()
        {
            return Queue.Count;
        }
        #endregion

        #region 对列处理机制和监控机制
        /// <summary>
        /// 初始化方法
        /// </summary>
        private void Init()
        {
            logsService.AddLogQueue("Init", InterfaceName.ApiLogQueue, "运行线程日志Init", "Init", 0, CommonHelp.ServiceIp);
            Task.Factory.StartNew(t =>
            {
                logsService.AddLogQueue("Init", InterfaceName.ApiLogQueue, "运行线程日志Init-->StartNew", "Init", 0, CommonHelp.ServiceIp);
                while (true)
                {
                    //判断消费队列是否小于某个值
                    try
                    {
                        var queueCount = GetCount();
                        //批量获取日志写入数据库
                        //logsService.AddModelBatch(Dequeue(SystemConst.Queue.ApiLogQueueCount));
                        if (queueCount >= SystemConst.Queue.ApiLogQueueCount && queueCount <= SystemConst.Queue.ApiLogQueueDangerCount)
                        {
                            LastWriteTime = DateTime.Now;
                            //批量获取日志写入数据库
                            logsService.AddModelBatch(Dequeue(SystemConst.Queue.ApiLogQueueCount));
                        }
                        else if (DateTime.Now >= LastWriteTime.AddMinutes(1))
                        {
                            LastWriteTime = DateTime.Now;
                            var apiLogs = Dequeue(queueCount);
                            if (apiLogs.Count > 0)
                            {
                                //批量获取日志写入数据库
                                logsService.AddModelBatch(apiLogs);
                                apiLogs.Clear();
                            }
                        }
                        #region 自己的运行日志
                        if (DateTime.Now.Minute == SystemConst.Queue.ApiWriteLogMinute && !IsWriteInitLog)
                        {
                            logsService.AddLogQueue("Init", InterfaceName.ApiLogQueue,
                                string.Format("运行线程日志Init-->StartNew-->while,当前对列数量:[{0}],时间:{1},IsWriteInitLog:{2}", queueCount, DateTime.Now.Minute, !IsWriteInitLog),
                                "Init", queueCount, CommonHelp.ServiceIp);
                            IsWriteInitLog = true;
                        }
                        else if (DateTime.Now.Minute > SystemConst.Queue.ApiWriteLogMinute && IsWriteInitLog)
                        {
                            IsWriteInitLog = false;
                        }
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        logsService.AddLogQueue(ApiLogType.Error, 0, InterfaceName.ApiLogQueue, ex.ToString(), string.Empty, "Init", 0, CommonHelp.ServiceIp);
                    }
                    //Thread.Sleep(100);
                    Thread.Sleep(10);
                }

            }, null);
        }

        /// <summary>
        /// 初始化监控方法
        /// </summary>
        private void InitMonitoring()
        {
            logsService.AddLogQueue("InitMonitoring", InterfaceName.ApiLogQueue, "监控线程日志InitMonitoring", "InitMonitoring", 0, CommonHelp.ServiceIp);

            Task.Factory.StartNew(t =>
            {
                logsService.AddLogQueue("InitMonitoring", InterfaceName.ApiLogQueue, "监控线程日志InitMonitoring-->StartNew", "InitMonitoring", 0, CommonHelp.ServiceIp);
                while (true)
                {
                    //判断消费队列是否小于某个值
                    try
                    {
                        var queueCount = GetCount();
                        if (queueCount > SystemConst.Queue.ApiLogQueueWarningCount)
                        {
                            var content = string.Format("接口日志对列已到达报警值{0},当前对列数量为:[{1}].", SystemConst.Queue.ApiLogQueueWarningCount, queueCount);
                            //记录报警日志
                            logsService.AddLogQueue("InitMonitoring", InterfaceName.ApiLogQueue, content, "InitMonitoring", 0, CommonHelp.ServiceIp);
                            //发报警邮件
                            //new EmailUtils().SendWarningEmail("ApiLogQueueService", "InitMonitoring", content, LogType.Warning);

                            LastWriteTime = DateTime.Now;
                            logsService.AddModelBatch(Dequeue(queueCount));
                        }
                        #region 接口日志对列已到达危险值报警
                        if (queueCount > SystemConst.Queue.ApiLogQueueDangerCount)//ApiLogQueueDangerCount
                        {
                            var content = string.Format("接口日志对列已到达危险值{0},当前对列数量为:[{1}].", SystemConst.Queue.ApiLogQueueDangerCount, queueCount);
                            //记录报警日志
                            logsService.AddLogQueue("InitMonitoring", InterfaceName.ApiLogQueue, content, "InitMonitoring", 0, CommonHelp.ServiceIp);
                            //发报警邮件
                            //new EmailUtils().SendWarningEmail("ApiLogQueueService", "InitMonitoring", content, LogType.Error);
                        }
                        #endregion

                        #region 监控线程自己运行日志
                        if (DateTime.Now.Hour == SystemConst.Queue.ApiWriteLogHour && !IsWriteMonitorLog)
                        {
                            logsService.AddLogQueue("InitMonitoring", InterfaceName.ApiLogQueue, string.Format("监控线程日志InitMonitoring-->StartNew-->while,当前对列数量:[{0}]", queueCount),
                                "InitMonitoring", queueCount, CommonHelp.ServiceIp);
                            IsWriteMonitorLog = true;
                        }
                        else if (DateTime.Now.Hour > SystemConst.Queue.ApiWriteLogHour && IsWriteInitLog)
                        {
                            IsWriteMonitorLog = false;
                        }
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        logsService.AddLogQueue(ApiLogType.Error, 0, InterfaceName.ApiLogQueue, ex.ToString(), string.Empty, "InitMonitoring", 0, CommonHelp.ServiceIp);
                    }
                    Thread.Sleep(1000);//1秒监控一次
                }

            }, null);
        }
        #endregion

        public void AddLog()
        {
            logsService.AddLogQueue("AddLog", InterfaceName.ApiLogQueue, "对列测试日志AddLog1", "AddLog", 0, CommonHelp.ServiceIp);
            logsService.AddModelBatch(Dequeue(SystemConst.Queue.ApiLogQueueCount));
            logsService.AddLogQueue("AddLog", InterfaceName.ApiLogQueue, "对列测试日志AddLog1", "AddLog", 0, CommonHelp.ServiceIp);
        }

        public void AddLog(string className, string method, ApiLogType logType, int projectId, int code, string requestData, string responseData, string remark, int resultCode, long elapsedTime, string createdBy, string search1 = "", string search2 = "")
        {
            logsService.AddLog(className, method, logType, projectId, code, requestData, responseData, remark, resultCode, elapsedTime, createdBy, search1, search2);
        }
    }

调用

BaseController

/// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="interfaceName"></param>
        /// <param name="className"></param>
        /// <param name="method"></param>
        /// <param name="reqModel">请求参数对象</param>
        /// <param name="rspModel">请求参数对象</param>
        /// <param name="resultCode">请求参数对象</param>
        /// <param name="sw">计时器对象</param>
        /// <param name="search1">查询条件1</param>
        /// <param name="search2">查询条件2</param>
        /// <param name="logType">日志类型</param>
        protected void AddLogElapsedTime(InterfaceName interfaceName, string className, string method, object reqModel, object rspModel, int resultCode, Stopwatch sw, Exception ex, string search1 = "", string search2 = "", ApiLogType logType = ApiLogType.Common)
        {
            sw.Stop();
            ApiLogQueueService.Instance.Enqueue(new ApiLogServiceModel()
            {
                Search1 = search1.SubstringExtend(100),
                Search2 = search2.SubstringExtend(100),
                ClassName = className.SubstringExtend(100),
                Method = method.SubstringExtend(100),
                Type = ex == null ? ApiLogType.Common.GetHashCode() : ApiLogType.Error.GetHashCode(),
                RequestModel = reqModel,
                ResponseModel = rspModel,
                ElapsedTime = sw.ElapsedMilliseconds,
                Code = interfaceName.GetHashCode(),
                InterfaceNameEnum = interfaceName,
                ProjectId = ProjectId.GetHashCode(),
                ResultCode = resultCode,
                Remark = ex != null ? string.Format("errorMsg:{0},Exception:{1}", ex.Message, ex.ToString()) : string.Empty,
                RowStatus = TrueOrFalseEnum.True.GetHashCode(),
                CreatedBy = CurrentUserId,
                CreatedOn = DateTime.Now,
                UpdatedBy = CommonHelp.ServiceIp,
            });
        }

net core API 过滤器调用

/// <summary>
    /// api 日志跟踪类
    /// </summary>
    public class ApiTrackerAttribute : ActionFilterAttribute
    {
        private string _prefix = "Tracker_";

        /// <summary>
        /// 控制器方法执行之前执行此方法
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var sw = new Stopwatch();
            sw.Start();
            context.HttpContext.Items.Add(_prefix + "params", context.ActionArguments);//请求开始实际带上
            var executeStartTime = DateTime.Now;
            context.HttpContext.Items.Add(_prefix + "executeStartTime", executeStartTime.ToString("yyyy-MM-dd HH:mm:ss:ffff"));
            //context.HttpContext.Items.Add(_prefix + "executeStartTimeffff", executeStartTime.ToString("yyyy-MM-dd HH:mm:ss:ffff"));
            context.HttpContext.Items.Add(_prefix + "sw", sw);
            context.HttpContext.Items.Add(_prefix + "ControllerName", ((ControllerActionDescriptor)context.ActionDescriptor).ControllerName);
            context.HttpContext.Items.Add(_prefix + "ActionName", ((ControllerActionDescriptor)context.ActionDescriptor).ActionName);

            return base.OnActionExecutionAsync(context, next);

        }

        /// <summary>
        /// 控制器操作结果执行之前调用此方法
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public override Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            WriteLogAsyncResult(context);
            return base.OnResultExecutionAsync(context, next);
        }

        /// <summary>
        /// 控制器操作结果执行之后调用此方法
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            //WriteLogAsync(context);
            base.OnActionExecuted(context);
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="actionContext"></param>
        /// <returns></returns>
        private bool WriteLogAsyncResult(ResultExecutingContext actionContext)
        {
            var isSucceed = false;
            var log = "0";
            try
            {
                ObjectResult resultObj = null;
                if (actionContext.Result != null)
                {
                    resultObj = actionContext.Result as Microsoft.AspNetCore.Mvc.ObjectResult;
                }
                //var resultJosn = JsonConvert.SerializeObject(resultObj.Value);
                log = "1";
                var items = actionContext.HttpContext.Items;
                log = "2";
                Stopwatch sw = null;
                if (items.ContainsKey(_prefix + "sw"))
                {
                    sw = items[_prefix + "sw"] as Stopwatch;
                }
                log = "3";
                var executeStartTimefffStr = string.Empty;
                if (items.ContainsKey(_prefix + "executeStartTime"))
                {
                    executeStartTimefffStr = items[_prefix + "executeStartTime"].ToString();
                }
                log = "4";
                var executeStartTimeStr = string.Empty;
                var fffStr = string.Empty;
                var executeStartTime = DateTime.Now;
                if (!string.IsNullOrEmpty(executeStartTimefffStr))
                {
                    if (executeStartTimefffStr.Length >= 19)
                    {
                        executeStartTimeStr = executeStartTimefffStr.Substring(0, 19);
                    }
                    if (executeStartTimefffStr.Length >= 24)
                    {
                        log = "5";
                        fffStr = executeStartTimefffStr.Substring(20, 4);
                    }
                    executeStartTime = DateTime.Parse(executeStartTimeStr);
                }                
                //log = "6";
                var fffStr_int = fffStr.ToInt();
                //log = "7";
                var controllerName = string.Empty;
                if (items.ContainsKey(_prefix + "ControllerName"))
                {
                    controllerName = items[_prefix + "ControllerName"].ToString();
                }
                var method = string.Empty;
                if (items.ContainsKey(_prefix + "ActionName"))
                {
                    method = items[_prefix + "ActionName"].ToString();
                }
                //log = "8";
                //var executeStartTime = DateTime.Parse(items[_prefix + "executeStartTime"].ToString());
                //var executeStartTimefff = items[_prefix + "executeStartTimeffff"].ToString();
                //executeStartTime.AddMilliseconds(fffStr.ToInt());
                //var aa = 0;
                #region MyRegion
                //WebApiLogModel logModel = new WebApiLogModel();
                //logModel.ExecuteStartTime = executeStartTime;
                //logModel.ExecuteEndTime = DateTime.Now;
                ////获取Action 参数
                //logModel.ActionParams = new Dictionary<string, object>(actionContext.ActionArguments);
                //logModel.HttpRequestHeaders = actionContext.HttpContext.Request.Headers.ToString();
                //logModel.HttpRequestPath = actionContext.HttpContext.Request.Path;
                //logModel.HttpMethod = actionContext.HttpContext.Request.Method;
                //logModel.ActionName = ((ControllerActionDescriptor)actionContext.ActionDescriptor).ActionName;
                //logModel.ControllerName = ((ControllerActionDescriptor)actionContext.ActionDescriptor).ControllerName;
                //logModel.TotalSeconds = (logModel.ExecuteEndTime - logModel.ExecuteStartTime).TotalSeconds;
                //logModel.IP = CommonHttpContext.Current.Connection.RemoteIpAddress.ToString(); 
                #endregion
                IDictionary<string, object> actionArguments = null;
                if (items.ContainsKey(_prefix + "params"))
                {
                    actionArguments = (IDictionary<string, object>)items[_prefix + "params"];
                    log = "9";
                }
                var logModel = new ApiLogServiceModel()
                {
                    Search1 = string.Empty,
                    Search2 = string.Empty,
                    ClassName = controllerName,
                    Method = method,
                    Type = ApiLogType.Common.GetHashCode(),
                    RequestModel = actionArguments,
                    ResponseModel = resultObj != null ? resultObj.Value : null,
                    Code = 0,
                    InterfaceNameEnum = InterfaceName.All,
                    ProjectId = ProjectIdEnum.LDApi.GetHashCode(),
                    ResultCode = 200,
                    ExecuteStartTime = executeStartTime,//DateTime.Parse(items[_prefix + "executeStartTime"].ToString()),
                    ExecuteEndTime = DateTime.Now,
                    Remark = string.Empty,
                    RowStatus = TrueOrFalseEnum.True.GetHashCode(),
                    CreatedBy = CommonHelp.ServiceIp,//CommonHttpContext.Current.Connection.RemoteIpAddress.ToString(),
                    CreatedOn = DateTime.Now,
                    UpdatedBy = CommonHelp.ServiceIp
                };
                log = "10";
                var totalMilliseconds = (logModel.ExecuteEndTime - logModel.ExecuteStartTime).TotalMilliseconds;
                log = "11";
                if ((totalMilliseconds - fffStr_int) >= 0)
                {
                    logModel.TimeDifference = totalMilliseconds - fffStr_int;
                }
                else
                {
                    logModel.TimeDifference = totalMilliseconds;
                }
                log = "12";
                logModel.Remark = string.Format("ExecuteStartTime:{0},executeStartTimefff:{1},ExecuteEndTime:{2},fffStr:{3}", executeStartTime.ToString("yyyy-MM-dd HH:mm:ss:fffff"), executeStartTimefffStr, logModel.ExecuteEndTime.ToString("yyyy-MM-dd HH:mm:ss:fffff"), fffStr);
                log = "13";
                if (sw != null)
                {
                    sw.Stop();
                    log = "14";
                    logModel.ElapsedTime = sw.ElapsedMilliseconds;
                }                
                log = "15";
                ApiLogQueueService.Instance.Enqueue(logModel);
                log = "16";
                isSucceed = true;
                log = "17";
            }
            catch (Exception ex)
            {
                var logModel = new ApiLogServiceModel()
                {
                    Search1 = string.Empty,
                    Search2 = string.Empty,
                    ClassName = "ApiTrackerAttribute",
                    Method = "WriteLogAsync",
                    Type = ApiLogType.Error.GetHashCode(),
                    RequestModel = null,
                    RequestData = String.Format("log:{0}", log),
                    ResponseModel = null,
                    ElapsedTime = 0,
                    Code = 0,
                    InterfaceNameEnum = InterfaceName.All,
                    ProjectId = ProjectIdEnum.LDApi.GetHashCode(),
                    ResultCode = 0,
                    TimeDifference = 0,
                    ExecuteStartTime = SystemConst.DateTimeDefault,
                    ExecuteEndTime = SystemConst.DateTimeDefault,
                    Remark = string.Format("errorMsg:{0},Exception:{1}", ex.Message, ex.ToString()),
                    RowStatus = TrueOrFalseEnum.True.GetHashCode(),
                    CreatedBy = CommonHelp.ServiceIp,
                    CreatedOn = DateTime.Now,
                    UpdatedBy = CommonHelp.ServiceIp,
                };
                ApiLogQueueService.Instance.Enqueue(logModel);
            }
            return isSucceed;
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="actionContext"></param>
        /// <returns></returns>
        private async Task WriteLogAsync(ActionExecutedContext actionContext)
        {
            try
            {
                var items = actionContext.HttpContext.Items;
                var sw = items[_prefix + "sw"] as Stopwatch;
                var executeStartTime = DateTime.Parse(items[_prefix + "executeStartTime"].ToString());
                #region MyRegion
                //WebApiLogModel logModel = new WebApiLogModel();
                //logModel.ExecuteStartTime = executeStartTime;
                //logModel.ExecuteEndTime = DateTime.Now;
                ////获取Action 参数
                //logModel.ActionParams = new Dictionary<string, object>(actionContext.ActionArguments);
                //logModel.HttpRequestHeaders = actionContext.HttpContext.Request.Headers.ToString();
                //logModel.HttpRequestPath = actionContext.HttpContext.Request.Path;
                //logModel.HttpMethod = actionContext.HttpContext.Request.Method;
                //logModel.ActionName = ((ControllerActionDescriptor)actionContext.ActionDescriptor).ActionName;
                //logModel.ControllerName = ((ControllerActionDescriptor)actionContext.ActionDescriptor).ControllerName;
                //logModel.TotalSeconds = (logModel.ExecuteEndTime - logModel.ExecuteStartTime).TotalSeconds;
                //logModel.IP = CommonHttpContext.Current.Connection.RemoteIpAddress.ToString(); 
                
                #endregion
                IDictionary<string, object> actionArguments = null;
                if (items.ContainsKey(_prefix + "params"))
                {
                    actionArguments = (IDictionary<string, object>)items[_prefix + "params"];
                }
                var logModel = new ApiLogServiceModel()
                {
                    Search1 = string.Empty,
                    Search2 = string.Empty,
                    ClassName = items[_prefix + "ControllerName"].ToString(),
                    Method = items[_prefix + "ActionName"].ToString(),
                    Type = ApiLogType.Common.GetHashCode(),
                    RequestModel = actionArguments,
                    ResponseModel = null,
                    Code = 0,
                    InterfaceNameEnum = InterfaceName.All,
                    ProjectId = ProjectIdEnum.LDApi.GetHashCode(),
                    ResultCode = 200,
                    ExecuteStartTime = executeStartTime,//DateTime.Parse(items[_prefix + "executeStartTime"].ToString()),
                    ExecuteEndTime = DateTime.Now,
                    Remark = string.Empty,
                    RowStatus = TrueOrFalseEnum.True.GetHashCode(),
                    CreatedBy = CommonHelp.ServiceIp,//CommonHttpContext.Current.Connection.RemoteIpAddress.ToString(),
                    CreatedOn = DateTime.Now,
                    UpdatedBy = CommonHelp.ServiceIp
                };
                logModel.TimeDifference = (logModel.ExecuteEndTime - logModel.ExecuteStartTime).TotalMilliseconds;
                logModel.Remark = string.Format("ExecuteStartTime:{0},ExecuteEndTime:{1}", executeStartTime.ToString("yyyy-MM-dd HH:mm:ss:fffff"), logModel.ExecuteEndTime.ToString("yyyy-MM-dd HH:mm:ss:fffff"));
                sw.Stop();
                logModel.ElapsedTime = sw.ElapsedMilliseconds;
                ApiLogQueueService.Instance.Enqueue(logModel);
            }
            catch (Exception ex)
            {
                var logModel = new ApiLogServiceModel()
                {
                    Search1 = string.Empty,
                    Search2 = string.Empty,
                    ClassName = "ApiTrackerAttribute",
                    Method = "WriteLogAsync",
                    Type = ApiLogType.Error.GetHashCode(),
                    RequestModel = string.Empty,
                    ResponseModel = null,
                    ElapsedTime = 0,
                    Code = 0,
                    InterfaceNameEnum = InterfaceName.All,
                    ProjectId = ProjectIdEnum.LDApi.GetHashCode(),
                    ResultCode = 0,
                    TimeDifference = 0,
                    ExecuteStartTime = SystemConst.DateTimeDefault,
                    ExecuteEndTime = SystemConst.DateTimeDefault,
                    Remark = string.Format("errorMsg:{0},Exception:{1}", ex.Message, ex.ToString()),
                    RowStatus = TrueOrFalseEnum.True.GetHashCode(),
                    CreatedBy = CommonHelper.CommonHelp.ServiceIp,
                    CreatedOn = DateTime.Now
                };
                ApiLogQueueService.Instance.Enqueue(logModel);
            }
        }
    }

配置服务

public void ConfigureServices(IServiceCollection services)
{
//在startup的ConfigureServices中设置或禁用WebApiExceptionFilterAttribute或WebApiTrackerAttribute
            services.AddControllers(ops =>
            {
                ops.Filters.Add(new ApiExceptionFilterAttribute());
                ops.Filters.Add(new ApiTrackerAttribute());
            }).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
}

 

posted @ 2016-04-15 23:24  baivfhpwxf  阅读(17849)  评论(2编辑  收藏  举报