LogService.cs 17.6 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
using HHECS.Application.Enums;
using HHECS.BllModel;
using HHECS.Application.Error;
using HHECS.Dal.Repository;
using HHECS.Infrastructure.Enums;
using HHECS.Model.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using HHECS.Infrastructure.Json;

namespace HHECS.Application.Service
{
    /// <summary>
    /// 日志服务类
    /// </summary>
    public class LogService : BaseService
    {

        #region 日志查询

        public BllResult<List<InterfaceLog>> GetInterfaceLogs(Expression<Func<InterfaceLog, bool>> exp, int pageIndex, int pageSize, out long totalCount)
        {
            try
            {
                using var interfaceLogRepository = new InterfaceLogRepository();
                var query = interfaceLogRepository.Where(exp);
                totalCount = query.Count();
                var result = query.OrderByDescending(a => a.Created).Page(pageIndex, pageSize).ToList();
                return BllResultFactory.Success(result);
            }
            catch (Exception ex)
            {
                totalCount = 0;
                return BllResultFactory.Error<List<InterfaceLog>>($"异常:{ex.Message}", ErrorCodeConst.DEZ0001.ToString());
            }
        }

        public BllResult<List<InterfaceLog>> GetInterfaceLogs(Expression<Func<InterfaceLog, bool>> exp)
        {
            try
            {
                InterfaceLogRepository interfaceLogRepository = new InterfaceLogRepository();
                var result = interfaceLogRepository.Where(exp).OrderByDescending(a => a.Created).ToList();
                return BllResultFactory.Success(result);
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error<List<InterfaceLog>>($"异常:{ex.Message}", ErrorCodeConst.DEZ0001.ToString());
            }
        }

        public BllResult<List<ContentLog>> GetContentLogs(Expression<Func<ContentLog, bool>> exp, int pageIndex, int pageSize, out long totalCount)
        {
            try
            {
                using var contentLogRepository = new ContentLogRepository();
                var query = contentLogRepository.Where(exp);
                totalCount = query.Count();
                var result = query.OrderByDescending(a => a.Created).Page(pageIndex, pageSize).ToList();
                return BllResultFactory.Success(result);
            }
            catch (Exception ex)
            {
                totalCount = 0;
                return BllResultFactory.Error<List<ContentLog>>($"异常:{ex.Message}", ErrorCodeConst.DEZ0001.ToString());
            }
        }

        public BllResult<List<ContentLog>> GetContentLogs(Expression<Func<ContentLog, bool>> exp)
        {
            try
            {
                ContentLogRepository contentLogRepository = new ContentLogRepository();
                var result = contentLogRepository.Where(exp).OrderByDescending(a => a.Created).ToList();
                return BllResultFactory.Success(result);
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error<List<ContentLog>>($"异常:{ex.Message}", ErrorCodeConst.DEZ0001.ToString());
            }
        }

        public BllResult<List<OperationLog>> GetOperationLogs(Expression<Func<OperationLog, bool>> exp, int pageIndex, int pageSize, out long totalCount)
        {
            try
            {
                using var operationLogRepository = new OperationLogRepository();
                var query = operationLogRepository.Where(exp);
                totalCount = query.Count();
                var result = query.OrderByDescending(a => a.Created).Page(pageIndex, pageSize).ToList();
                return BllResultFactory.Success(result);
            }
            catch (Exception ex)
            {
                totalCount = 0;
                return BllResultFactory.Error<List<OperationLog>>($"异常:{ex.Message}", ErrorCodeConst.DEZ0001.ToString());
            }
        }

        public BllResult<List<OperationLog>> GetOperationLogs(Expression<Func<OperationLog, bool>> exp)
        {
            try
            {
                OperationLogRepository operationLogRepository = new OperationLogRepository();
                var result = operationLogRepository.Where(exp).OrderByDescending(a => a.Created).ToList();
                return BllResultFactory.Success(result);
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error<List<OperationLog>>($"异常:{ex.Message}", ErrorCodeConst.DEZ0001.ToString());
            }
        }

        #endregion

        #region 日志记录

        /// <summary>
        /// 记录接口日志到数据库
        /// </summary>
        public BllResult LogInterface(string interfaceName, string url, string request, string Response, Level flag, string content, string remark, string createdBy, DateTime? startTime, DateTime? endTime)
        {
            try
            {
                InterfaceLog interfaceLog = new InterfaceLog()
                {
                    InterfaceName = interfaceName,
                    Url = url,
                    Request = request,
                    Response = Response,
                    Flag = flag.ToString(),
                    Content = content,
                    Remark = remark,
                    CreatedBy = createdBy,
                    UpdatedBy = createdBy,
                    Created = startTime,
                    Updated = endTime
                };
                InterfaceLogRepository interfaceLogRepository = new InterfaceLogRepository();
                interfaceLogRepository.Insert(interfaceLog);
                return BllResultFactory.Success();
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error<List<InterfaceLog>>($"异常:{ex.Message}", ErrorCodeConst.DEZ0001.ToString());
            }
        }

        /// <summary>
        /// 记录接口日志到数据库
        /// </summary>
        public BllResult LogInterface(string interfaceName, string request, string Response, string flag, string content, long totalMilliseconds, string remark, string url = null, string method = null)
        {
            try
            {
                InterfaceLog interfaceLog = new InterfaceLog();
                interfaceLog.InterfaceName = interfaceName;
                interfaceLog.Request = request;
                interfaceLog.Response = Response;
                interfaceLog.Url = url;
                interfaceLog.Method = method;
                interfaceLog.Flag = flag;
                interfaceLog.Content = content;
                interfaceLog.TotalMilliseconds = (int)totalMilliseconds;
                interfaceLog.Remark = remark;
                interfaceLog.CreatedBy = Accounts.WCSInterface.ToString();
                interfaceLog.Created = DateTime.Now;
                InterfaceLogRepository interfaceLogRepository = new InterfaceLogRepository();
                interfaceLogRepository.Insert(interfaceLog);
                return BllResultFactory.Success();
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error(ex.Message, ErrorCodeConst.DEZ0001.ToString());
            }
        }



        /// <summary>
        /// 记录普通日志到数据库
        /// </summary>
        public BllResult LogContent(Title logTitle, string log, string userCode, Level flag)
        {
            try
            {
                ContentLog contentLog = new ContentLog()
                {
                    Title = logTitle.ToString(),
                    Content = log,
                    Flag = flag.ToString(),
                    Created = DateTime.Now,
                    CreatedBy = userCode
                };
                ContentLogRepository contentLogRepository = new ContentLogRepository();
                contentLogRepository.Insert(contentLog);
                return BllResultFactory.Success();
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error<List<InterfaceLog>>($"异常:{ex.Message}", ErrorCodeConst.DEZ0001.ToString());
            }
        }

        /// <summary>
        /// /// <summary>
        /// 记录操作日志
        /// </summary>
        /// <param name="noticeTitle">通知标题</param>
        /// <param name="moduleConst">系统模块</param>
        /// <param name="content">内容</param>
        /// <param name="result">状态</param>
        /// <param name="userCode">用户</param>
        /// <returns></returns>
        public BllResult LogOperation(Title noticeTitle, ModuleConst moduleConst, string content, string result, string userCode)
        {
            try
            {
                using OperationLogRepository operationLogRepository = new OperationLogRepository();
                operationLogRepository.Insert(new OperationLog()
                {
                    Title = noticeTitle.ToString(),
                    Module = moduleConst.ToString(),
                    Content = content,
                    Result = result,
                    Created = DateTime.Now,
                    CreatedBy = userCode,
                });
                return BllResultFactory.Success();
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error($"异常:{ex.Message}", ErrorCodeConst.DEZ0001.ToString());
            }
        }

        /// <summary>
        /// 记录业务返回日志
        /// </summary>
        public void LogBllResult(BllResult bllResult, Title title, string userCode)
        {
            LogContent(title, bllResult.Msg, userCode, bllResult.Success ? Level.Success : Level.Failure);
        }

        /// <summary>
        /// 记录业务返回日志
        /// </summary>
        public void LogBllResult<T>(BllResult<T> bllResult, Title title, string userCode)
        {
            LogContent(title, bllResult.Msg, userCode, bllResult.Success ? Level.Success : Level.Failure);
        }

        #endregion


        #region Web日志记录

        public string Load(WebOperationLog webOperationLog, int pageIndex, int pageSize)
        {
            return Execute(() =>
            {
                using var webOperationLogRepository = new WebOperationLogRepository();
                var query = webOperationLogRepository.Where(GetExpression(webOperationLog));
                var result = query.OrderByDescending(a => a.OperationTime).Page(pageIndex, pageSize).ToList();
                Response.Result = result;
                Response.Count = query.Count();
                return Response.ToJson();
            });
        }

        public Expression<Func<WebOperationLog, bool>> GetExpression(WebOperationLog operationLog)
        {
            Expression<Func<WebOperationLog, bool>> filter = t => true;
            if (!String.IsNullOrWhiteSpace(operationLog.PermissionName))
            {
                filter = filter.And(t => t.PermissionName == operationLog.PermissionName);
            }
            if (operationLog.Result != null)
            {
                filter = filter.And(t => t.Result == operationLog.Result);
            }
            if (!String.IsNullOrWhiteSpace(operationLog.Operator))
            {
                filter = filter.And(t => t.Operator.Contains(operationLog.Operator));
            }
            if (!String.IsNullOrWhiteSpace(operationLog.OperType))
            {
                filter = filter.And(t => t.OperType == operationLog.OperType);
            }
            if (!String.IsNullOrWhiteSpace(operationLog.IP))
            {
                filter = filter.And(t => t.IP.Contains(operationLog.IP));
            }
            if (!String.IsNullOrWhiteSpace(operationLog.Url))
            {
                filter = filter.And(t => t.Url.Contains(operationLog.Url));
            }
            if (!String.IsNullOrWhiteSpace(operationLog.Method))
            {
                filter = filter.And(t => t.Method.Contains(operationLog.Method));
            }
            if (operationLog.TotalSeconds != 0)
            {
                filter = filter.And(t => t.TotalSeconds <= operationLog.TotalSeconds);
            }
            if (!String.IsNullOrWhiteSpace(operationLog.Request))
            {
                filter = filter.And(t => t.Request.Contains(operationLog.Request));
            }
            if (!String.IsNullOrWhiteSpace(operationLog.Response))
            {
                filter = filter.And(t => t.Response.Contains(operationLog.Response));
            }
            if (operationLog.End != null && operationLog.Start != null)
            {
                filter = filter.And(t => t.OperationTime <= operationLog.End && t.OperationTime >= operationLog.Start);
            }
            else if (operationLog.End != null)
            {
                filter = filter.And(t => t.OperationTime <= operationLog.End);
            }
            else if (operationLog.Start != null)
            {
                filter = filter.And(t => t.OperationTime >= operationLog.Start);
            }
            return filter;
        }


        /// <summary>
        /// /// <summary>
        /// 新增记录操作日志
        /// </summary>
        /// <param name="url"></param>
        /// <param name="operType"></param>
        /// <param name="method"></param>
        /// <param name="request"></param>
        /// <param name="parameter"></param>
        /// <param name="Response"></param>
        /// <param name="totalSeconds">执行时间(秒)</param>
        /// <param name="user"></param>
        /// <param name="ip">IP地址</param>
        /// <param name="result">执行结果</param>
        /// <param name="permissionName"></param>
        /// <returns></returns>
        public BllResult AddWebOperationLog(string url, string operType, string method, string request, string parameter, string Response, double totalSeconds, User user, string ip, bool result, string permissionName)
        {
            try
            {
                new WebOperationLogRepository().Insert(new WebOperationLog()
                {
                    PermissionName = permissionName,
                    Url = url,
                    OperType = operType,
                    Method = method,
                    Request = request,
                    Parameter = parameter,
                    Response = Response,
                    TotalSeconds = Math.Round(totalSeconds, 2),
                    Operator = user?.UserCode,
                    UserId = user?.Id,
                    Result = result,
                    OperationAddress = IsPrivateNetwork(ip) ? "内网IP" : "外网IP",
                    IP = ip,
                    OperationTime = DateTime.Now
                });
                return BllResultFactory.Success();
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error($"异常:{ex.Message}", ErrorCodeConst.DEZ0001.ToString());
            }
        }

        static bool IsPrivateNetwork(string ipv4Address) => IPAddress.TryParse(ipv4Address, out var ip) && ip.GetAddressBytes() switch
        {
            var x when x[0] == 10 => true,
            var x when x[0] == 127 => true,
            var x when x[0] == 0 => true,
            var x when x[0] == 172 && x[1] >= 16 && x[1] <= 31 => true,
            var x when x[0] == 192 && x[1] == 168 => true,
            _ => false
        };

        /// <summary>
        /// 获取操作日志
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public string GetOperationLog(OperationLog entity, int page, int limit)
        {
            return Execute(() =>
            {
                using var operationLogRepository = new OperationLogRepository();
                var query = operationLogRepository.Where(GetExpression(entity));
                var result = query.OrderByDescending(a => a.Created).Page(page, limit).ToList();
                Response.Result = result.Select(x => new
                {
                    x.Id,
                    x.Module,
                    ModuleName = Enum.Parse(typeof(ModuleConst), x.Module),
                    x.Title,
                    TitleName = Enum.Parse(typeof(Title), x.Title),
                    x.Content,
                    x.Result,
                    x.Created,
                    x.CreatedBy
                }).ToList();
                Response.Count = query.Count();
                return Response.ToJson();
            });
        }

        private Expression<Func<OperationLog, bool>> GetExpression(OperationLog entity)
        {
            Expression<Func<OperationLog, bool>> filter = t => true;
            if (!string.IsNullOrWhiteSpace(entity.Module))
            {
                filter = filter.And(t => t.Module.Equals(entity.Module));
            }
            if (!string.IsNullOrWhiteSpace(entity.Title))
            {
                filter = filter.And(x => x.Title.Equals(entity.Title));
            }
            if (!string.IsNullOrWhiteSpace(entity.CreatedBy))
            {
                filter = filter.And(x => x.CreatedBy.Equals(entity.CreatedBy));
            }
            return filter;
        }


        public string Export(WebOperationLog entity)
        {
            return Execute(() =>
            {
                var result = new WebOperationLogRepository().Where(GetExpression(entity)).OrderByDescending(a => a.Created).ToList();
                Response.Result = result;
                Response.Count = result.Count;
                return Response.ToJson();
            });
        }
        #endregion
    }
}