LogService.cs 19.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
using System;
using System.Collections.Generic;
using System.Text;
using Hh.Mes.Common.log;
using Hh.Mes.Common.Request;
using Hh.Mes.POJO.Entity;
using Hh.Mes.Pojo.System;
using Hh.Mes.Service.Repository;
using SqlSugar;
using Hh.Mes.POJO.Response;
using Hh.Mes.Service.SystemAuth;
using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;


namespace Hh.Mes.Service.Logs
{
    /// <summary>
    /// 日志类
    /// </summary>
    public class LogService : RepositorySqlSugar<sys_interface_log>
    {
        private readonly IDistributedCache _cache;

        public LogService(IAuth auth, IDistributedCache cache) : base(auth, cache)
        {
            _cache = cache;
        }

        public LogService()
        {
            
        }

        #region 接口日志
        /// <summary>
        /// //获取列表
        /// </summary>
        public Response LoadSysInterLog(PageReq pageReq, sys_interface_log model)
        {
            var result = new Response();

            string orderBy = (pageReq == null || string.IsNullOrEmpty(pageReq.field)) ? " id desc" : $"{pageReq.field} {pageReq.order} ";
            string sqlWhere = SqlSysInterLogWhere(model);
            var stringBuilder = new StringBuilder();
            //页码,页数
            //Exel ture 不分页
            if (!model.Exel && pageReq != null)
            {
                stringBuilder.Append("declare @pageIndex int,@pageSize int,@offset int");
                stringBuilder.AppendLine($"  select @pageIndex={pageReq.page}, @pageSize={pageReq.limit}, @offset=(@pageIndex - 1) * @pageSize");
            }

            stringBuilder.AppendLine($@" select  t1.* 
                                         from [dbo].sys_interface_log t1    with(nolock)
                                         where {sqlWhere}
                                         order by {orderBy} ");

            //Exel ture 不分页
            if (!model.Exel)
            {
                stringBuilder.AppendLine("  offset @offset row fetch next @pageSize row only ");
                stringBuilder.Append($" select rowTotal= count(*) from sys_interface_log  t1  with(nolock) where {sqlWhere}");
            }
            var ds = base.Context.Ado.GetDataSetAll(stringBuilder.ToString(), new List<SugarParameter>(){
                new SugarParameter("@type",model.type),
                new SugarParameter("@name",model.name),
                new SugarParameter("@system",model.system),
                new SugarParameter("@path",model.path),
                new SugarParameter("@actionName",model.actionName),
                new SugarParameter("@beginLogTime",model.BeginLogTime),
                new SugarParameter("@endLogTime",model.EndLogTime),
                new SugarParameter("@response",model.response),

                new SugarParameter("@request",model.request),
            });

            result.Result = ds.Tables[0];
            result.Count = model.Exel ? (int)result.Result.Rows.Count : (int)ds.Tables[1].Rows[0]["rowTotal"];
            return result;
        }

        private string SqlSysInterLogWhere(sys_interface_log model)
        {
            var stringBuilder = new StringBuilder();
            stringBuilder.Append("1=1");
            if (!string.IsNullOrWhiteSpace(model.type)) stringBuilder.Append(" and  t1.type =@type ");
            if (!string.IsNullOrWhiteSpace(model.name)) stringBuilder.Append(" and  t1.name like  '%'+@name+'%' ");
            if (!string.IsNullOrWhiteSpace(model.system)) stringBuilder.Append(" and  t1.system like  '%'+@system+'%' ");
            if (!string.IsNullOrWhiteSpace(model.path)) stringBuilder.Append(" and  t1.path like  '%'+@path+'%' ");
            if (!string.IsNullOrWhiteSpace(model.actionName)) stringBuilder.Append(" and  t1.actionName like  '%'+@actionName+'%' ");
            if (model.BeginLogTime != null) stringBuilder.Append(" and  t1.logTime > @beginLogTime ");
            if (model.EndLogTime != null) stringBuilder.Append(" and  t1.logTime < @endLogTime ");

            if (model.response != null) stringBuilder.Append(" and  t1.response like  '%'+@response+'%' ");
            if (!string.IsNullOrEmpty(model.responseNo200)) {
                stringBuilder.Append(" and  t1.response not like  '%200%' ");
                stringBuilder.Append(" and  t1.response not like  '返回结果只处理%' ");
            }


            if (model.request != null) stringBuilder.Append(" and  t1.request like  '%'+@request+'%' ");
            return stringBuilder.ToString();
        }

        /// <summary>
        /// 新增接口日志  稳定后批量
        /// </summary>
        /// <returns></returns>
        public void InsSysInterLog(List<sys_interface_log> model)
        {
            try
            {
                base.Context.Insertable(model).ExecuteCommand();
            }
            catch (Exception e)
            {
                var actionName = model[0].actionName;
                var apiGroup = model[0].apiGroup;
                var browser = model[0].browser;
                var flag = model[0].flag;
                var logTime = model[0].logTime;
                var method = model[0].method;
                var request = model[0].request;
                var response = model[0].response;
                var server = model[0].server;
                var totalMilliseconds = 0;
                var type = model[0].type;
                var queryString = model[0].queryString;
                var name = model[0].name;
                var ip = model[0].ip;
                var path = model[0].path;
                var system = model[0].system;
                var result = model[0].result;
                var remark = model[0].remark;
                var msg = $@"actionName:【{actionName}】,apiGroup:【{apiGroup}】,browser:【{browser}】,flag:【{flag}】,logTime:【{logTime}】,method:【{method}】
                            request:{request}】,response:{response}】,server:{server}】,totalMilliseconds:{totalMilliseconds}】,type:{type}】,queryString:{queryString}
                            name:{name}】,ip:{ip}】,path:{path}】,system:{system}】,result:{result}】,remark:{remark}";
                Log4NetHelper.Instance.Info(msg);
                Log4NetHelper.Instance.Error(e.Message);
            }
        }

        #endregion

        #region 操作日志
        /// <summary>
        /// //获取列表
        /// </summary>
        public Response LoadSysOperLog(PageReq pageReq, sys_oper_log model)
        {
            var result = new Response();

            string orderBy = (pageReq == null || string.IsNullOrEmpty(pageReq.field)) ? " id desc" : $"{pageReq.field} {pageReq.order} ";
            string sqlWhere = SqlSysOperLogWhere(model);
            var stringBuilder = new StringBuilder();
            //页码,页数
            //Exel ture 不分页
            if (!model.Exel && pageReq != null)
            {
                stringBuilder.Append("declare @pageIndex int,@pageSize int,@offset int");
                stringBuilder.AppendLine($"  select @pageIndex={pageReq.page}, @pageSize={pageReq.limit}, @offset=(@pageIndex - 1) * @pageSize");
            }

            stringBuilder.AppendLine($@" select  t1.* 
                                         from [dbo].sys_oper_log t1    with(nolock)
                                         where {sqlWhere}
                                         order by {orderBy} ");

            //Exel ture 不分页
            if (!model.Exel)
            {
                stringBuilder.AppendLine("  offset @offset row fetch next @pageSize row only ");
                stringBuilder.Append($" select rowTotal= count(*) from sys_oper_log  t1  with(nolock) where {sqlWhere}");
            }
            var ds = base.Context.Ado.GetDataSetAll(stringBuilder.ToString(), new List<SugarParameter>(){
                new SugarParameter("@name",model.name),
                new SugarParameter("@operType",model.operType),
                new SugarParameter("@logTime",model.logTime),
            });

            result.Result = ds.Tables[0];
            result.Count = model.Exel ? (int)result.Result.Rows.Count : (int)ds.Tables[1].Rows[0]["rowTotal"];
            return result;
        }

        private string SqlSysOperLogWhere(sys_oper_log model)
        {
            var stringBuilder = new StringBuilder();
            stringBuilder.Append("1=1");
            if (model.logTime != null) stringBuilder.Append(" and  t1.logTime >=@logTime ");
            if (!string.IsNullOrWhiteSpace(model.name)) stringBuilder.Append(" and  t1.name like  '%'+@name+'%' ");
            if (!string.IsNullOrWhiteSpace(model.operType)) stringBuilder.Append(" and  t1.operType =@operType ");
            return stringBuilder.ToString();
        }
        #endregion

        #region 定时器日志
        /// <summary>
        /// //获取列表
        /// </summary>
        public Response LoadSysJobLog(PageReq pageReq, sys_job_log model)
        {
            var result = new Response();

            string orderBy = (pageReq == null || string.IsNullOrEmpty(pageReq.field)) ? " id desc " : $"{pageReq.field} {pageReq.order} ";
            string sqlWhere = SqlSysJobLogWhere(model);
            var stringBuilder = new StringBuilder();
            //页码,页数
            //Exel ture 不分页
            if (!model.Exel && pageReq != null)
            {
                stringBuilder.Append("declare @pageIndex int,@pageSize int,@offset int");
                stringBuilder.AppendLine($"  select @pageIndex={pageReq.page}, @pageSize={pageReq.limit}, @offset=(@pageIndex - 1) * @pageSize");
            }

            stringBuilder.AppendLine($@" select  t1.* 
                                         from [dbo].sys_job_log t1    with(nolock)
                                         where {sqlWhere}
                                         order by {orderBy} ");

            //Exel ture 不分页
            if (!model.Exel)
            {
                stringBuilder.AppendLine("  offset @offset row fetch next @pageSize row only ");
                stringBuilder.Append($" select rowTotal= count(*) from sys_job_log  t1  with(nolock) where {sqlWhere}");
            }
            var ds = base.Context.Ado.GetDataSetAll(stringBuilder.ToString(), new List<SugarParameter>(){
                new SugarParameter("@jobName",model.jobName),
                new SugarParameter("@createTime",model.createTime)
            });

            result.Result = ds.Tables[0];
            result.Count = model.Exel ? (int)result.Result.Rows.Count : (int)ds.Tables[1].Rows[0]["rowTotal"];
            return result;
        }

        private string SqlSysJobLogWhere(sys_job_log model)
        {
            var stringBuilder = new StringBuilder();
            stringBuilder.Append("1=1");
            if (!string.IsNullOrWhiteSpace(model.jobName)) stringBuilder.Append(" and  t1.jobName =@jobName ");
            if (model.createTime != null) stringBuilder.Append(" and  t1.createTime >@createTime ");
            return stringBuilder.ToString();
        }


        /// <summary>
        /// 新增 定时器日志 稳定后批量
        /// </summary>
        /// <returns></returns>
        public void InsSysJobLog(List<sys_job_log> model)
        {
            try
            {
                base.Context.Insertable(model).ExecuteCommand();
            }
            catch (Exception e)
            {
                var jobName = model[0].jobName;
                var methodName = model[0].methodName;
                var methodParams = model[0].methodParams;
                var jobMessage = model[0].jobMessage;
                var exceptionInfo = model[0].exceptionInfo;

                var msg = $@"jobName:【{jobName}】,methodName:【{methodName}】,methodParams:【{methodParams}】,
                             jobMessage:{jobMessage}】,exceptionInfo:{exceptionInfo}";
                Log4NetHelper.Instance.Info(msg);
                Log4NetHelper.Instance.Error(e.Message);
            }
        }
        #endregion

        #region  在线日志
        /// <summary>
        /// //获取列表
        /// </summary>
        public Response LoadSysUserOnlineLog(PageReq pageReq, sys_user_online model)
        {
            var result = new Response();

            string orderBy = (pageReq == null || string.IsNullOrEmpty(pageReq.field)) ? " id desc " : $"{pageReq.field} {pageReq.order} ";
            string sqlWhere = SqlSysUserOnlineLogWhere(model);
            var stringBuilder = new StringBuilder();
            //页码,页数
            //Exel ture 不分页
            if (!model.Exel && pageReq != null)
            {
                stringBuilder.Append("declare @pageIndex int,@pageSize int,@offset int");
                stringBuilder.AppendLine($"  select @pageIndex={pageReq.page}, @pageSize={pageReq.limit}, @offset=(@pageIndex - 1) * @pageSize");
            }

            stringBuilder.AppendLine($@" select  t1.* 
                                         from [dbo].sys_user_online t1    with(nolock)
                                         where {sqlWhere}
                                         order by {orderBy} ");

            //Exel ture 不分页
            if (!model.Exel)
            {
                stringBuilder.AppendLine("  offset @offset row fetch next @pageSize row only ");
                stringBuilder.Append($" select rowTotal= count(*) from sys_user_online  t1  with(nolock) where {sqlWhere}");
            }
            var ds = base.Context.Ado.GetDataSetAll(stringBuilder.ToString(), new List<SugarParameter>(){
                new SugarParameter("@account",model.account)
            });

            result.Result = ds.Tables[0];
            result.Count = model.Exel ? (int)result.Result.Rows.Count : (int)ds.Tables[1].Rows[0]["rowTotal"];
            return result;
        }

        private string SqlSysUserOnlineLogWhere(sys_user_online model)
        {
            var stringBuilder = new StringBuilder();
            stringBuilder.Append("1=1");
            if (!string.IsNullOrWhiteSpace(model.account)) stringBuilder.Append(" and  t1.account=@account ");
            return stringBuilder.ToString();
        }


        public dynamic Logout(List<sys_user_online> model)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                foreach (var item in model)
                {
                    Context.Deleteable<sys_user_online>().Where(u => u.id == item.id).AddQueue();
                    _cache.Remove(item.token);
                }
                if (Context.SaveQueues() <= 0)
                {
                    response.Code = 500;
                    response.Message = SystemVariable.dataActionError;
                    return response;
                }
                return response;
            });

        }

        public dynamic Logout(string token)
        {
            var response = new Response();

            var userAuthSessionBytes = _cache.Get(token);
            if (userAuthSessionBytes != null)
            {
                var userAuthSession = JsonSerializer.Deserialize<UserAuthSession>(userAuthSessionBytes);
                _cache.Remove(userAuthSession.Account);
                _cache.Remove(token);
            }

            Context.Deleteable<sys_user_online>().Where(u => u.token == token).ExecuteCommand();
            return response;
        }
        #endregion

        #region  登入日志
        /// <summary>
        /// //获取列表
        /// </summary>
        public Response LoadSysLoginLog(PageReq pageReq, sys_login_log model)
        {
            var result = new Response();

            string orderBy = (pageReq == null || string.IsNullOrEmpty(pageReq.field)) ? " id desc " : $"{pageReq.field} {pageReq.order} ";
            string sqlWhere = SqlSysLoginLogWhere(model);
            var stringBuilder = new StringBuilder();
            //页码,页数
            //Exel ture 不分页
            if (!model.Exel && pageReq != null)
            {
                stringBuilder.Append("declare @pageIndex int,@pageSize int,@offset int");
                stringBuilder.AppendLine($"  select @pageIndex={pageReq.page}, @pageSize={pageReq.limit}, @offset=(@pageIndex - 1) * @pageSize");
            }

            stringBuilder.AppendLine($@" select  t1.* 
                                         from [dbo].sys_login_log t1    with(nolock)
                                         where {sqlWhere}
                                         order by {orderBy} ");

            //Exel ture 不分页
            if (!model.Exel)
            {
                stringBuilder.AppendLine("  offset @offset row fetch next @pageSize row only ");
                stringBuilder.Append($" select rowTotal= count(*) from sys_login_log  t1  with(nolock) where {sqlWhere}");
            }
            var ds = base.Context.Ado.GetDataSetAll(stringBuilder.ToString(), new List<SugarParameter>(){
                new SugarParameter("@account",model.account)
            });

            result.Result = ds.Tables[0];
            result.Count = model.Exel ? (int)result.Result.Rows.Count : (int)ds.Tables[1].Rows[0]["rowTotal"];
            return result;
        }

        private string SqlSysLoginLogWhere(sys_login_log model)
        {
            var stringBuilder = new StringBuilder();
            stringBuilder.Append("1=1");
            if (!string.IsNullOrWhiteSpace(model.account)) stringBuilder.Append(" and  t1.account=@account ");
            return stringBuilder.ToString();
        }

        #endregion

        #region 登入页面 登入成功之后
        /// <summary>
        /// 是否存在数据 在线用户
        /// </summary>
        /// <returns></returns>
        public bool loginAfter(sys_login_log mode)
        {
            var isExt = base.Context.Queryable<sys_user_online>().Where(x => x.ipaddr == mode.ipaddr && x.account == mode.account).Any();
            var sysUserOnline = new sys_user_online
            {
                token = mode.token,
                userId = mode.id,
                account = mode.account,
                name = mode.name,
                ipaddr = mode.ipaddr,
                browser = mode.browser,
                loginTime = DateTime.Now,
            };
            if (isExt)
            {
                UpdataSysUserOnLine(sysUserOnline);
            }
            else
            {
                InsSysUserOnLine(sysUserOnline);
            }
            InsSysLoginLog(mode);
            base.Context.SaveQueues();
            return isExt;
        }

        /// <summary>
        /// 新增登入日志
        /// </summary>
        /// <returns></returns>
        public void InsSysLoginLog(sys_login_log model)
        {
            model.createBy = model.account;
            model.createTime = DateTime.Now;
            base.Context.Insertable(model).AddQueue();
        }

        /// <summary>
        /// 新增 在线用户
        /// </summary>
        /// <returns></returns>
        public void InsSysUserOnLine(sys_user_online model)
        {
            model.createBy = model.account;
            model.createTime = DateTime.Now;
            base.Context.Insertable(model).AddQueue();
        }


        /// <summary>
        /// 更新在线用户时间、 token 、lastAccessTime
        /// </summary>
        public void UpdataSysUserOnLine(sys_user_online model)
        {
            model.updateBy = model.account;
            model.updateTime = DateTime.Now;
            base.Context.Updateable(model).Where(x => x.ipaddr == model.ipaddr && x.account == model.account)
                .UpdateColumns(x => new { x.token, x.loginTime, x.lastAccessTime }).AddQueue();
        }
        #endregion

        public ISqlSugarClient GetContext()
        {
            return base.Context;
        }
    }
}