日志

parent 079d5d4b
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FluentValidation.AspNetCore;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Performance.DtoModels;
using Performance.DtoModels.AppSettings;
using Performance.Infrastructure;
using Performance.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Performance.Api.Controllers
{
[Route("api/[controller]")]
public class ModExtractController : Controller
{
private readonly ILogger<ModExtractController> logger;
private ModExtractService modExtractService;
private WebapiUrl url;
public ModExtractController(ModExtractService modExtractService,
public ModExtractController(
ILogger<ModExtractController> logger,
ModExtractService modExtractService,
IOptions<WebapiUrl> url)
{
this.logger = logger;
this.modExtractService = modExtractService;
this.url = url.Value;
}
......@@ -155,7 +160,7 @@ public ApiResponse AddItem([FromBody]ItemListRequest request)
[HttpPost]
public ApiResponse Items([FromBody]ModItemRequest request)
{
LogHelper.Information(url.HttpPost + "/modextract/items", "请求地址");
logger.LogInformation($"请求地址 {url.HttpPost}/modextract/items");
HttpHelper.HttpPost(url.HttpPost + "/modextract/items", JsonHelper.Serialize(request), true);
var list = modExtractService.Items(request.ModuleId.Value);
return new ApiResponse(ResponseType.OK, list);
......
......@@ -238,7 +238,7 @@ public ApiResponse NewExtractData([CustomizeValidator, FromBody]ExtractRequest r
request.Email = email;
//if (request.UseScheme == (int)UseTemplate.Config)
//{
LogHelper.Information("请求路径:" + url.HttpPost + "/extract/extract", "提取绩效数据");
logger.LogInformation("提取绩效数据请求路径:" + url.HttpPost + "/extract/extract");
HttpHelper.HttpPostNoRequest(url.HttpPost + "/extract/extract", JsonHelper.Serialize(request), true);
//}
//else
......@@ -307,14 +307,14 @@ public IActionResult DownFile([FromQuery]AllotRequest request)
[AllowAnonymous]
public ApiResponse SaveFile([FromForm] IFormCollection form, int allotId, int hospitalId)
{
LogHelper.Information($"请求参数:allotId:{allotId} hospitalId:{hospitalId}", "保存提取文件");
logger.LogInformation($"保存提取文件请求参数:allotId:{allotId} hospitalId:{hospitalId}");
logger.LogInformation($"保存提取文件 参数:allotId:{allotId} hospitalId:{hospitalId}");
try
{
var file = ((FormFileCollection)form.Files).FirstOrDefault();
if (file == null)
{
LogHelper.Error($"返回文件为空!", "保存提取文件");
logger.LogError($"返回文件为空!");
return new ApiResponse(ResponseType.Error, "上传文件无效");
}
......@@ -322,7 +322,7 @@ public ApiResponse SaveFile([FromForm] IFormCollection form, int allotId, int ho
FileHelper.CreateDirectory(dpath);
var path = Path.Combine(dpath, FileHelper.GetFileName(file.FileName));
LogHelper.Information($"保存路径:" + path, "保存提取文件");
logger.LogInformation($"保存提取文件保存路径:" + path);
using (var stream = file.OpenReadStream())
{
......@@ -330,7 +330,7 @@ public ApiResponse SaveFile([FromForm] IFormCollection form, int allotId, int ho
stream.Read(bytes, 0, bytes.Length);
if (!FileHelper.CreateFile(path, bytes))
{
LogHelper.Error($"保存失败", "保存提取文件");
logger.LogError($"保存提取文件保存失败");
return new ApiResponse(ResponseType.Error, "保存失败");
}
}
......@@ -339,12 +339,12 @@ public ApiResponse SaveFile([FromForm] IFormCollection form, int allotId, int ho
allot.IsExtracting = 2;
if (string.IsNullOrEmpty(path) || !FileHelper.IsExistFile(path))
{
LogHelper.Information($"文件未保存成功,保存文件不存在!", "保存提取文件");
logger.LogInformation($"保存提取文件文件未保存成功,保存文件不存在!");
return new ApiResponse(ResponseType.Fail, "上传成功!");
}
if (!allotService.Update(allot))
{
LogHelper.Information($"更新文件路径失败!", "保存提取文件");
logger.LogInformation($"保存提取文件更新文件路径失败!");
return new ApiResponse(ResponseType.Fail, "上传成功!");
}
return new ApiResponse(ResponseType.OK, "上传成功!");
......@@ -352,7 +352,7 @@ public ApiResponse SaveFile([FromForm] IFormCollection form, int allotId, int ho
catch (Exception ex)
{
logger.LogInformation($"保存提取文件异常{ex.ToString()}");
LogHelper.Error($"保存失败:" + ex.ToString(), "保存提取文件");
logger.LogError($"保存提取文件保存失败:" + ex.ToString());
return new ApiResponse(ResponseType.Error, ex.Message);
}
}
......
......@@ -57,7 +57,6 @@ public ActionsFilter(ILoggerFactory factory, IMemoryCache cache, IHostingEnviron
context.Result = new ObjectResult(response);
var jsonData = JsonHelper.Serialize(context.Result);
_logger.LogInformation($"响应结果:{jsonData}");
LogHelper.Information($"请求地址:{context.HttpContext.Request.Path};响应结果:{jsonData}", "响应结果");
}
//记录response结果
......@@ -69,11 +68,10 @@ public ActionsFilter(ILoggerFactory factory, IMemoryCache cache, IHostingEnviron
if (executedContext.Result is ObjectResult)
{
LogHelper.Information(JsonHelper.Serialize(executedContext.Result), "响应结果");
_logger.LogInformation("响应结果" + JsonHelper.Serialize(executedContext.Result));
var objectResult = (ObjectResult)executedContext.Result;
var jsonData = JsonHelper.Serialize(objectResult.Value);
_logger.LogInformation($"响应结果:{jsonData}");
LogHelper.Information($"请求地址:{context.HttpContext.Request.Path};响应结果:{jsonData}", "响应结果");
_logger.LogInformation($"请求地址:{context.HttpContext.Request.Path};响应结果:{jsonData}");
}
}
}
......
......@@ -26,21 +26,21 @@ public Task OnExceptionAsync(ExceptionContext context)
_logger.LogWarning($"接口错误警告:{context.Exception.ToString()}");
var response = new ApiResponse(ResponseType.Fail, context.Exception.Message);
context.Result = new ObjectResult(response);
LogHelper.Warning(JsonHelper.Serialize(response), "接口错误警告");
_logger.LogWarning("接口错误警告" + JsonHelper.Serialize(response));
}
else if (context.Exception is PerformanceTokenErrorException)
{
_logger.LogWarning($"Token Error:{context.Exception.ToString()}");
var response = new ApiResponse(ResponseType.TokenError, context.Exception.Message);
context.Result = new ObjectResult(response);
LogHelper.Warning(JsonHelper.Serialize(response), "Token Error");
_logger.LogWarning("Token Error" + JsonHelper.Serialize(response));
}
else
{
_logger.LogError($"接口异常:{context.Exception.ToString()}");
var response = new ApiResponse(ResponseType.Error, "接口内部异常", context.Exception.Message);
context.Result = new ObjectResult(response);
LogHelper.Error(JsonHelper.Serialize(response), "接口内部异常");
_logger.LogError("接口内部异常" + JsonHelper.Serialize(response));
}
return Task.CompletedTask;
}
......
......@@ -48,7 +48,7 @@ public Startup(IConfiguration configuration)
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
LogHelper.Initialize(Configuration.GetSection("AppConnection:RedisConnectionString").Value, "MTEzMTAyMzEzNDYzMzY5MzE4NA");
//LogHelper.Initialize(Configuration.GetSection("AppConnection:RedisConnectionString").Value, "MTEzMTAyMzEzNDYzMzY5MzE4NA");
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
#region appsetting注入
......
......@@ -120,37 +120,35 @@ public void Index([FromBody]AllotRequest request)
[HttpPost]
public void ExtractData([CustomizeValidator, FromBody]ExtractRequest request)
{
LogHelper.Information("请求参数:" + JsonHelper.Serialize(request), "提取绩效数据");
logger.LogInformation("请求参数:" + JsonHelper.Serialize(request));
logger.LogInformation("提取绩效数据请求参数:" + JsonHelper.Serialize(request));
//string filePath = newExtractService.ExtractData(request.AllotId, request.Email, request.HospitalId);
string filePath = dfExtractService.ExtractData(request.AllotId, request.Email, request.HospitalId);
if (!string.IsNullOrEmpty(filePath) && FileHelper.IsExistFile(filePath))
{
logger.LogInformation("请求路径:" + url.ImportFile + ",请求参数" + JsonHelper.Serialize(new { allotId = request.AllotId, hospitalId = request.HospitalId }));
LogHelper.Information("请求路径:" + url.ImportFile + ",请求参数" + JsonHelper.Serialize(new { allotId = request.AllotId, hospitalId = request.HospitalId }), "保存提取文件");
int i = 1;
while (i <= 5)
{
if (i == 5)
LogHelper.Information($"保存文件失败,已尝试执行五次,请联系开发人员!", "保存提取文件");
logger.LogInformation($"保存文件失败,已尝试执行五次,请联系开发人员!");
else
LogHelper.Information($"正在尝试第{i}次保存!", "保存提取文件");
logger.LogInformation($"正在尝试第{i}次保存!");
//保存文件
string retJson = HttpHelper.HttpClient(url.ImportFile + $"?allotId={request.AllotId}&hospitalId={request.HospitalId}", filePath);
LogHelper.Information("返回结果:" + JsonHelper.Serialize(retJson), "保存提取文件");
logger.LogInformation("保存提取文件返回结果:" + JsonHelper.Serialize(retJson));
logger.LogInformation(retJson);
var ret = JsonHelper.Deserialize<ApiResponse>(retJson);
if (ret != null && (int)ret.State == 1)
{
LogHelper.Information("保存成功!", "保存提取文件");
logger.LogInformation("保存提取文件保存成功!");
break;
}
i++;
}
}
else
LogHelper.Information($"提取文件不存在!", "保存提取文件");
logger.LogInformation($"保存提取文件提取文件不存在!");
}
#endregion
......
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Performance.DtoModels;
using Performance.Infrastructure;
using Performance.Services;
......@@ -13,9 +14,13 @@ namespace Performance.Extract.Api.Controllers
[Route("api/[controller]")]
public class ModExtractController : Controller
{
private readonly ILogger<ModExtractController> logger;
private ModExtractService modExtractService;
public ModExtractController(ModExtractService modExtractService)
public ModExtractController(
ILogger<ModExtractController> logger,
ModExtractService modExtractService)
{
this.logger = logger;
this.modExtractService = modExtractService;
}
......@@ -59,7 +64,7 @@ public ApiResponse FeeSource([FromBody]ModModuleRequest request)
if (request.HospitalId == null || request.HospitalId.Value == 0)
return new ApiResponse(ResponseType.ParameterError, "HospitalId 参数错误!");
LogHelper.Information($"绩效考核项费用来源:{JsonHelper.Serialize(request)}", "请求参数");
logger.LogInformation($"请求参数绩效考核项费用来源:{JsonHelper.Serialize(request)}");
var list = modExtractService.FeeSource(request);
return new ApiResponse(ResponseType.OK, list);
}
......@@ -72,7 +77,7 @@ public ApiResponse FeeSource([FromBody]ModModuleRequest request)
[HttpPost]
public ApiResponse Items([FromBody]ModItemRequest request)
{
LogHelper.Information($"绩效收入模板配置项列表:{JsonHelper.Serialize(request)}", "请求参数");
logger.LogInformation($"绩效收入模板配置项列表:{JsonHelper.Serialize(request)}");
modExtractService.AddItems(request.ModuleId.Value);
return new ApiResponse(ResponseType.OK);
}
......
......@@ -26,21 +26,21 @@ public Task OnExceptionAsync(ExceptionContext context)
_logger.LogWarning($"接口错误警告:{context.Exception.ToString()}");
var response = new ApiResponse(ResponseType.Fail, context.Exception.Message);
context.Result = new ObjectResult(response);
LogHelper.Warning(JsonHelper.Serialize(response), "接口错误警告");
_logger.LogWarning("接口错误警告" + JsonHelper.Serialize(response));
}
else if (context.Exception is PerformanceTokenErrorException)
{
_logger.LogWarning($"Token Error:{context.Exception.ToString()}");
var response = new ApiResponse(ResponseType.TokenError, context.Exception.Message);
context.Result = new ObjectResult(response);
LogHelper.Warning(JsonHelper.Serialize(response), "Token Error");
_logger.LogWarning("Token Error" + JsonHelper.Serialize(response));
}
else
{
_logger.LogError($"接口异常:{context.Exception.ToString()}");
var response = new ApiResponse(ResponseType.Error, "接口内部异常", context.Exception.Message);
context.Result = new ObjectResult(response);
LogHelper.Error(JsonHelper.Serialize(response), "接口内部异常");
_logger.LogError("接口内部异常" + JsonHelper.Serialize(response));
}
return Task.CompletedTask;
}
......
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using AutoMapper;
using FluentValidation;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Builder;
......@@ -23,6 +16,13 @@
using Performance.EntityModels;
using Performance.Infrastructure;
using Performance.Services;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Performance.Extract.Api
{
......@@ -39,7 +39,7 @@ public Startup(IConfiguration configuration, IHostingEnvironment env)
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
LogHelper.Initialize(Configuration.GetSection("AppConnection:RedisConnectionString").Value, "MTEzMTAyMzEzNDYzMzY5MzE4NA");
//LogHelper.Initialize(Configuration.GetSection("AppConnection:RedisConnectionString").Value, "MTEzMTAyMzEzNDYzMzY5MzE4NA");
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
#region appsetting注入
......
using CSRedis;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
public static class LogHelper
{
private static AsyncLocal<string> _asyncLocal;
private static BlockingCollection<Log> _queue;
private static object _lockObject;
private static string _secretKey;
private static IHttpContextAccessor _contextAccessor;
public static void Initialize(string redisConnectionString, string secretKey)
{
_secretKey = secretKey;
var client = new CSRedisClient(redisConnectionString);
_queue = new BlockingCollection<Log>();
_asyncLocal = new AsyncLocal<string>();
_lockObject = new object();
_contextAccessor = new HttpContextAccessor();
Task.Factory.StartNew(() =>
{
while (!_queue.IsCompleted)
{
var log = _queue.Take();
client.LPush("log.queue", log);
}
});
}
public static void Trace(string message, params string[] tag)
{
WriteLog(message, tag, LogLevel.Trace);
}
public static void Debug(string message, params string[] tag)
{
WriteLog(message, tag, LogLevel.Debug);
}
public static void Information(string message, params string[] tag)
{
WriteLog(message, tag, LogLevel.Information);
}
public static void Warning(string message, params string[] tag)
{
WriteLog(message, tag, LogLevel.Warning);
}
public static void Error(string message, params string[] tag)
{
WriteLog(message, tag, LogLevel.Error);
}
public static void Fatal(string message, params string[] tag)
{
WriteLog(message, tag, LogLevel.Fatal);
}
private static void WriteLog(string message, string[] tag, LogLevel logLevel)
{
try
{
if (_contextAccessor.HttpContext == null || string.IsNullOrEmpty(_contextAccessor.HttpContext.TraceIdentifier))
{
if (string.IsNullOrEmpty(_asyncLocal.Value))
lock (_lockObject)
Guid.NewGuid().ToString("N");
}
else
{
_asyncLocal.Value = _contextAccessor.HttpContext.TraceIdentifier;
}
Log log = new Log
{
Id = SnowflakeId.Default().NextId(),
Level = logLevel,
LogTime = DateTime.Now,
Message = message,
Stack = GetStackInfo(),
TraceId = _asyncLocal.Value,
Tag = tag.ToList(),
SecretKey = _secretKey
};
_queue.Add(log);
}
catch { }
}
private static List<string> GetStackInfo()
{
StackTrace trace = new StackTrace(true);
List<string> result = new List<string>();
for (int i = 0; i < trace.FrameCount; i++)
{
StackFrame frame = trace.GetFrame(i);
MethodBase method = frame.GetMethod();
if (method.DeclaringType == null
|| method.DeclaringType.FullName.StartsWith("System")
|| method.DeclaringType.FullName.StartsWith("Microsoft")
|| method.DeclaringType.FullName.StartsWith("Online.Log"))
continue;
var paras = method.GetParameters().Select(t => $"{t.ParameterType.Name} {t.Name}");
result.Add($"At {method.DeclaringType.FullName}.{method.Name}({string.Join(",", paras)}) Number({frame.GetFileLineNumber()})");
}
return result;
}
}
internal class Log
{
public long Id { get; set; }
public DateTime LogTime { get; set; }
public LogLevel Level { get; set; }
public string SecretKey { get; set; }
public string TraceId { get; set; }
public string Message { get; set; }
public List<string> Stack { get; set; }
public List<string> Tag { get; set; }
}
internal enum LogLevel
{
All = 0,
Trace = 1,
Debug = 2,
Information = 3,
Warning = 4,
Error = 5,
Fatal = 6
}
internal class SnowflakeId
{
public const long Twepoch = 1288834974657L;
private const int WorkerIdBits = 5;
private const int DatacenterIdBits = 5;
private const int SequenceBits = 12;
private const long MaxWorkerId = -1L ^ (-1L << WorkerIdBits);
private const long MaxDatacenterId = -1L ^ (-1L << DatacenterIdBits);
private const int WorkerIdShift = SequenceBits;
private const int DatacenterIdShift = SequenceBits + WorkerIdBits;
public const int TimestampLeftShift = SequenceBits + WorkerIdBits + DatacenterIdBits;
private const long SequenceMask = -1L ^ (-1L << SequenceBits);
private static SnowflakeId _snowflakeId;
private readonly object _lock = new object();
private static readonly object SLock = new object();
private long _lastTimestamp = -1L;
public SnowflakeId(long workerId, long datacenterId, long sequence = 0L)
{
WorkerId = workerId;
DatacenterId = datacenterId;
Sequence = sequence;
// sanity check for workerId
if (workerId > MaxWorkerId || workerId < 0)
throw new ArgumentException($"worker Id can't be greater than {MaxWorkerId} or less than 0");
if (datacenterId > MaxDatacenterId || datacenterId < 0)
throw new ArgumentException($"datacenter Id can't be greater than {MaxDatacenterId} or less than 0");
}
public long WorkerId { get; protected set; }
public long DatacenterId { get; protected set; }
public long Sequence { get; internal set; }
public static SnowflakeId Default()
{
lock (SLock)
{
if (_snowflakeId != null)
{
return _snowflakeId;
}
var random = new Random();
if (!int.TryParse(Environment.GetEnvironmentVariable("CAP_WORKERID", EnvironmentVariableTarget.Machine), out var workerId))
{
workerId = random.Next((int)MaxWorkerId);
}
if (!int.TryParse(Environment.GetEnvironmentVariable("CAP_DATACENTERID", EnvironmentVariableTarget.Machine), out var datacenterId))
{
datacenterId = random.Next((int)MaxDatacenterId);
}
return _snowflakeId = new SnowflakeId(workerId, datacenterId);
}
}
public virtual long NextId()
{
lock (_lock)
{
var timestamp = TimeGen();
if (timestamp < _lastTimestamp)
throw new Exception(
$"InvalidSystemClock: Clock moved backwards, Refusing to generate id for {_lastTimestamp - timestamp} milliseconds");
if (_lastTimestamp == timestamp)
{
Sequence = (Sequence + 1) & SequenceMask;
if (Sequence == 0) timestamp = TilNextMillis(_lastTimestamp);
}
else
{
Sequence = 0;
}
_lastTimestamp = timestamp;
var id = ((timestamp - Twepoch) << TimestampLeftShift) |
(DatacenterId << DatacenterIdShift) |
(WorkerId << WorkerIdShift) | Sequence;
return id;
}
}
protected virtual long TilNextMillis(long lastTimestamp)
{
var timestamp = TimeGen();
while (timestamp <= lastTimestamp) timestamp = TimeGen();
return timestamp;
}
protected virtual long TimeGen()
{
return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
}
}
//using CSRedis;
//using Microsoft.AspNetCore.Http;
//using System;
//using System.Collections.Concurrent;
//using System.Collections.Generic;
//using System.Diagnostics;
//using System.Linq;
//using System.Reflection;
//using System.Threading;
//using System.Threading.Tasks;
//public static class LogHelper
//{
// private static AsyncLocal<string> _asyncLocal;
// private static BlockingCollection<Log> _queue;
// private static object _lockObject;
// private static string _secretKey;
// private static IHttpContextAccessor _contextAccessor;
// public static void Initialize(string redisConnectionString, string secretKey)
// {
// _secretKey = secretKey;
// var client = new CSRedisClient(redisConnectionString);
// _queue = new BlockingCollection<Log>();
// _asyncLocal = new AsyncLocal<string>();
// _lockObject = new object();
// _contextAccessor = new HttpContextAccessor();
// Task.Factory.StartNew(() =>
// {
// while (!_queue.IsCompleted)
// {
// var log = _queue.Take();
// client.LPush("log.queue", log);
// }
// });
// }
// public static void Trace(string message, params string[] tag)
// {
// WriteLog(message, tag, LogLevel.Trace);
// }
// public static void Debug(string message, params string[] tag)
// {
// WriteLog(message, tag, LogLevel.Debug);
// }
// public static void Information(string message, params string[] tag)
// {
// WriteLog(message, tag, LogLevel.Information);
// }
// public static void Warning(string message, params string[] tag)
// {
// WriteLog(message, tag, LogLevel.Warning);
// }
// public static void Error(string message, params string[] tag)
// {
// WriteLog(message, tag, LogLevel.Error);
// }
// public static void Fatal(string message, params string[] tag)
// {
// WriteLog(message, tag, LogLevel.Fatal);
// }
// private static void WriteLog(string message, string[] tag, LogLevel logLevel)
// {
// try
// {
// if (_contextAccessor.HttpContext == null || string.IsNullOrEmpty(_contextAccessor.HttpContext.TraceIdentifier))
// {
// if (string.IsNullOrEmpty(_asyncLocal.Value))
// lock (_lockObject)
// Guid.NewGuid().ToString("N");
// }
// else
// {
// _asyncLocal.Value = _contextAccessor.HttpContext.TraceIdentifier;
// }
// Log log = new Log
// {
// Id = SnowflakeId.Default().NextId(),
// Level = logLevel,
// LogTime = DateTime.Now,
// Message = message,
// Stack = GetStackInfo(),
// TraceId = _asyncLocal.Value,
// Tag = tag.ToList(),
// SecretKey = _secretKey
// };
// _queue.Add(log);
// }
// catch { }
// }
// private static List<string> GetStackInfo()
// {
// StackTrace trace = new StackTrace(true);
// List<string> result = new List<string>();
// for (int i = 0; i < trace.FrameCount; i++)
// {
// StackFrame frame = trace.GetFrame(i);
// MethodBase method = frame.GetMethod();
// if (method.DeclaringType == null
// || method.DeclaringType.FullName.StartsWith("System")
// || method.DeclaringType.FullName.StartsWith("Microsoft")
// || method.DeclaringType.FullName.StartsWith("Online.Log"))
// continue;
// var paras = method.GetParameters().Select(t => $"{t.ParameterType.Name} {t.Name}");
// result.Add($"At {method.DeclaringType.FullName}.{method.Name}({string.Join(",", paras)}) Number({frame.GetFileLineNumber()})");
// }
// return result;
// }
//}
//internal class Log
//{
// public long Id { get; set; }
// public DateTime LogTime { get; set; }
// public LogLevel Level { get; set; }
// public string SecretKey { get; set; }
// public string TraceId { get; set; }
// public string Message { get; set; }
// public List<string> Stack { get; set; }
// public List<string> Tag { get; set; }
//}
//internal enum LogLevel
//{
// All = 0,
// Trace = 1,
// Debug = 2,
// Information = 3,
// Warning = 4,
// Error = 5,
// Fatal = 6
//}
//internal class SnowflakeId
//{
// public const long Twepoch = 1288834974657L;
// private const int WorkerIdBits = 5;
// private const int DatacenterIdBits = 5;
// private const int SequenceBits = 12;
// private const long MaxWorkerId = -1L ^ (-1L << WorkerIdBits);
// private const long MaxDatacenterId = -1L ^ (-1L << DatacenterIdBits);
// private const int WorkerIdShift = SequenceBits;
// private const int DatacenterIdShift = SequenceBits + WorkerIdBits;
// public const int TimestampLeftShift = SequenceBits + WorkerIdBits + DatacenterIdBits;
// private const long SequenceMask = -1L ^ (-1L << SequenceBits);
// private static SnowflakeId _snowflakeId;
// private readonly object _lock = new object();
// private static readonly object SLock = new object();
// private long _lastTimestamp = -1L;
// public SnowflakeId(long workerId, long datacenterId, long sequence = 0L)
// {
// WorkerId = workerId;
// DatacenterId = datacenterId;
// Sequence = sequence;
// // sanity check for workerId
// if (workerId > MaxWorkerId || workerId < 0)
// throw new ArgumentException($"worker Id can't be greater than {MaxWorkerId} or less than 0");
// if (datacenterId > MaxDatacenterId || datacenterId < 0)
// throw new ArgumentException($"datacenter Id can't be greater than {MaxDatacenterId} or less than 0");
// }
// public long WorkerId { get; protected set; }
// public long DatacenterId { get; protected set; }
// public long Sequence { get; internal set; }
// public static SnowflakeId Default()
// {
// lock (SLock)
// {
// if (_snowflakeId != null)
// {
// return _snowflakeId;
// }
// var random = new Random();
// if (!int.TryParse(Environment.GetEnvironmentVariable("CAP_WORKERID", EnvironmentVariableTarget.Machine), out var workerId))
// {
// workerId = random.Next((int)MaxWorkerId);
// }
// if (!int.TryParse(Environment.GetEnvironmentVariable("CAP_DATACENTERID", EnvironmentVariableTarget.Machine), out var datacenterId))
// {
// datacenterId = random.Next((int)MaxDatacenterId);
// }
// return _snowflakeId = new SnowflakeId(workerId, datacenterId);
// }
// }
// public virtual long NextId()
// {
// lock (_lock)
// {
// var timestamp = TimeGen();
// if (timestamp < _lastTimestamp)
// throw new Exception(
// $"InvalidSystemClock: Clock moved backwards, Refusing to generate id for {_lastTimestamp - timestamp} milliseconds");
// if (_lastTimestamp == timestamp)
// {
// Sequence = (Sequence + 1) & SequenceMask;
// if (Sequence == 0) timestamp = TilNextMillis(_lastTimestamp);
// }
// else
// {
// Sequence = 0;
// }
// _lastTimestamp = timestamp;
// var id = ((timestamp - Twepoch) << TimestampLeftShift) |
// (DatacenterId << DatacenterIdShift) |
// (WorkerId << WorkerIdShift) | Sequence;
// return id;
// }
// }
// protected virtual long TilNextMillis(long lastTimestamp)
// {
// var timestamp = TimeGen();
// while (timestamp <= lastTimestamp) timestamp = TimeGen();
// return timestamp;
// }
// protected virtual long TimeGen()
// {
// return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
// }
//}
......@@ -174,14 +174,14 @@ public string TemplateExecute(string email, per_allot lastAllot, sys_hospital ho
workbook.Write(file);
}
logManageService.WriteMsg("提取绩效数据", $"{hospital.HosName}HIS数据提取成功,文件路径:{newPath}。", 5, Allot.ID, "ReceiveMessage");
LogHelper.Information($"{hospital.HosName}HIS数据提取成功,文件路径:{newPath}。", "提取绩效数据");
logger.LogInformation($"提取绩效数据 {hospital.HosName}HIS数据提取成功,文件路径:{newPath}");
SendEmail(email, newPath, $"{hospital.HosName}HIS数据提取成功", $"{hospital.HosName}{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}成功提取。");
return newPath;
}
catch (Exception ex)
{
logManageService.WriteMsg("提取数据异常", $"数据写入出现异常", 4, Allot.ID, "ReceiveMessage");
LogHelper.Error($"数据写入出现异常{ex.ToString()}", "提取绩效数据", "异常");
logger.LogError($"提取绩效数据异常 数据写入出现异常{ex.ToString()}");
SendEmail(email, "", $"{hospital.HosName}HIS数据提取失败", $"{hospital.HosName}提取数据过程中出现异常情况,我们将尽快解决问题。给您带来的不便我们深感歉意!");
throw ex;
}
......@@ -257,14 +257,14 @@ public string AlllotExecute(string email, per_allot lastAllot, sys_hospital hosp
workbook.Write(file);
}
logManageService.WriteMsg("提取绩效数据", $"{hospital.HosName}HIS数据提取成功,文件路径:{newPath}。", 5, Allot.ID, "ReceiveMessage");
LogHelper.Information($"{hospital.HosName}HIS数据提取成功,文件路径:{newPath}。", "提取绩效数据");
logger.LogInformation($"提取绩效数据 {hospital.HosName}HIS数据提取成功,文件路径:{newPath}");
SendEmail(email, newPath, $"{hospital.HosName}HIS数据提取成功", $"{hospital.HosName}{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}成功提取。");
return newPath;
}
catch (Exception ex)
{
logManageService.WriteMsg("提取数据异常", $"数据写入出现异常", 4, Allot.ID, "ReceiveMessage");
LogHelper.Error($"数据写入出现异常{ex.ToString()}", "提取绩效数据", "异常");
logger.LogError($"提取绩效数据 异常 数据写入出现异常{ex.ToString()}");
SendEmail(email, "", $"{hospital.HosName}HIS数据提取失败", $"{hospital.HosName}提取数据过程中出现异常情况,我们将尽快解决问题。给您带来的不便我们深感歉意!");
throw ex;
}
......@@ -394,7 +394,7 @@ private void WriteOtherIncome(ISheet sheet, IPerSheetDataRead sheetRead, List<Ac
foreach (var moditem in category)
{
logManageService.WriteMsg("提取绩效数据", $"执行SQL脚本获取数据 -- {module.ModuleName}", 1, Allot.ID, "ReceiveMessage");
LogHelper.Information($"执行SQL脚本获取数据 -- {module.ModuleName},", "提取绩效数据");
logger.LogInformation($"提取绩效数据 执行SQL脚本获取数据 -- {module.ModuleName}");
var config = configs.FirstOrDefault(t => t.Id == moditem.ConfigId);
if (config == null) continue;
......@@ -426,7 +426,7 @@ private void WriteIncome(ISheet sheet, IPerSheetDataRead sheetRead, List<Account
foreach (var item in extractList)
{
logManageService.WriteMsg("提取绩效数据", $"执行SQL脚本获取数据 -- {module.ModuleName}", 1, Allot.ID, "ReceiveMessage");
LogHelper.Information($"执行SQL脚本获取数据 -- {module.ModuleName}", "提取绩效数据");
logger.LogInformation($"提取绩效数据 执行SQL脚本获取数据 -- {module.ModuleName}");
var config = configs.FirstOrDefault(t => t.Id == module.ConfigId);
if (config == null) continue;
......@@ -464,7 +464,7 @@ private void WriteWorkload(ISheet sheet, IPerSheetDataRead sheetRead, List<Accou
if (IsWriteHead)
{
logManageService.WriteMsg("提取绩效数据", $"写入列头信息 -- {module.ModuleName}", 1, Allot.ID, "ReceiveMessage");
LogHelper.Information($"写入列头信息 -- {module.ModuleName}", "提取绩效数据");
logger.LogInformation($"提取绩效数据 写入列头信息 -- {module.ModuleName}");
//写入列头信息
int cellStartIndex = sheetRead.Point.HeaderFirstCellNum.Value + 2;
foreach (var item in itemList)
......@@ -493,7 +493,7 @@ private void WriteWorkload(ISheet sheet, IPerSheetDataRead sheetRead, List<Accou
foreach (var moditem in category)
{
logManageService.WriteMsg("提取绩效数据", $"执行SQL脚本获取数据 -- {module.ModuleName}", 1, Allot.ID, "ReceiveMessage");
LogHelper.Information($"执行SQL脚本获取数据 -- {module.ModuleName},", "提取绩效数据");
logger.LogInformation($"提取绩效数据 执行SQL脚本获取数据 -- {module.ModuleName}");
var config = configs.FirstOrDefault(t => t.Id == moditem.ConfigId);
if (config == null) continue;
......@@ -511,7 +511,7 @@ private void WriteWorkload(ISheet sheet, IPerSheetDataRead sheetRead, List<Accou
}
logManageService.WriteMsg("提取绩效数据", $"填充数据 -- {module.ModuleName}", 1, Allot.ID, "ReceiveMessage");
LogHelper.Information($"填充数据 -- {module.ModuleName}", "提取绩效数据");
logger.LogInformation($"提取绩效数据 填充数据 -- {module.ModuleName}");
//写入数据
var rowIndex = sheetRead.Point.HeaderFirstRowNum.Value + 2;
foreach (var department in allExtract.Select(t => t.Department).Distinct())
......@@ -569,7 +569,7 @@ private void WriteWorkload(ISheet sheet, IPerSheetDataRead sheetRead, List<Accou
// };
// logManageService.WriteMsg("提取绩效数据", $"填充数据 -- 临床科室医护绩效测算表", 1, Allot.ID, "ReceiveMessage");
// LogHelper.Information($"填充数据 -- 临床科室医护绩效测算表", "提取绩效数据");
// logger.Information($"填充数据 -- 临床科室医护绩效测算表", "提取绩效数据");
// var dataList = perforImaccountbasicRepository.GetEntities(t => t.AllotID == allotLastId)?.OrderBy(t => t.UnitType).ThenBy(t => t.DoctorAccountingUnit).ToList();
// for (int i = 0; i < dataList.Count; i++)
// {
......@@ -626,7 +626,7 @@ private void WriteSpecialUnit(ISheet sheet, IPerSheetDataRead sheetRead, List<sy
// foreach (var specialitem in category)
// {
// logManageService.WriteMsg("提取绩效数据", $"执行SQL脚本获取数据 -- 特殊核算单元绩效测算表", 1, Allot.ID, "ReceiveMessage");
// LogHelper.Information($"执行SQL脚本获取数据 -- 特殊核算单元绩效测算表,", "提取绩效数据");
// logger.Information($"执行SQL脚本获取数据 -- 特殊核算单元绩效测算表,", "提取绩效数据");
// var config = configs.FirstOrDefault(t => t.Id == specialitem.ConfigId);
// if (config == null) continue;
......@@ -655,7 +655,7 @@ private void WriteSpecialUnit(ISheet sheet, IPerSheetDataRead sheetRead, List<sy
int mergedEnd = sheetRead.Point.DataFirstRowNum.Value;
logManageService.WriteMsg("提取绩效数据", $"填充数据 -- 特殊核算单元绩效测算表", 1, Allot.ID, "ReceiveMessage");
LogHelper.Information($"填充数据 -- 特殊核算单元绩效测算表", "提取绩效数据");
logger.LogInformation($"提取绩效数据 填充数据 -- 特殊核算单元绩效测算表");
for (int i = 0; i < speaialList.Count; i++)
{
var headIndex = sheetRead.Point.HeaderFirstRowNum;
......@@ -683,7 +683,7 @@ private void WriteSpecialUnit(ISheet sheet, IPerSheetDataRead sheetRead, List<sy
if (cell.StringCellValue == "数量" && speaialList[i]?.ExtractId > 0)
{
logManageService.WriteMsg("提取绩效数据", $"执行SQL脚本获取数据 -- 特殊核算单元绩效测算表", 1, Allot.ID, "ReceiveMessage");
LogHelper.Information($"执行SQL脚本获取数据 -- 特殊核算单元绩效测算表,", "提取绩效数据");
logger.LogInformation($"提取绩效数据 执行SQL脚本获取数据 -- 特殊核算单元绩效测算表 ");
var config = configs.FirstOrDefault(t => t.Id == speaialList[i].ConfigId);
if (config == null) continue;
......@@ -719,7 +719,7 @@ private void WriteHeaderAndFactor(ISheet sheet, IPerSheetDataRead sheetRead, Lis
var head = GetOrCreate(sheet, sheetRead.Point.HeaderFirstRowNum.Value);
logManageService.WriteMsg("提取绩效数据", $"写入列头信息 -- {sheet.SheetName}", 1, Allot.ID, "ReceiveMessage");
LogHelper.Information($"写入列头信息 -- {sheet.SheetName}", "提取绩效数据");
logger.LogInformation($"提取绩效数据 提取绩效数据 写入列头信息 -- {sheet.SheetName}");
//写入列头信息
int cellStartIndex = sheetRead.Point.HeaderFirstCellNum.Value + 4;
foreach (var item in items)
......@@ -746,7 +746,7 @@ private void WriteHeaderAndFactor(ISheet sheet, IPerSheetDataRead sheetRead, Lis
private void WriteSheetData(ISheet sheet, IPerSheetDataRead sheetRead, List<AccountUnitEntity> unitList, List<ExtractDto> allExtract)
{
logManageService.WriteMsg("提取绩效数据", $"填充数据 -- {sheet.SheetName}", 1, Allot.ID, "ReceiveMessage");
LogHelper.Information($"填充数据 -- {sheet.SheetName}", "提取绩效数据");
logger.LogInformation($"提取绩效数据 填充数据 -- {sheet.SheetName}");
//写入数据
var head = GetOrCreate(sheet, sheetRead.Point.HeaderFirstRowNum.Value);
var rowIndex = sheetRead.Point.HeaderFirstRowNum.Value + 1;
......@@ -809,7 +809,7 @@ private List<ExtractDto> QueryDatabase(sys_hospitalconfig config, mod_extract ex
executeScript = Regex.Replace(executeScript, item.Key, item.Value, RegexOptions.IgnoreCase);
}
//logManageService.WriteMsg("提取绩效数据", $"SQL脚本:{executeScript}", 1, AllotId, "ReceiveMessage");
LogHelper.Information($"SQL脚本{executeScript},", "提取绩效数据");
logger.LogInformation($"提取绩效数据 SQL脚本{executeScript}");
var result = connection.Query<ExtractDto>(executeScript, commandTimeout: 20000);
if (result != null && result.Count() > 0)
{
......
......@@ -95,7 +95,7 @@ public string GetFilepath(int hospitalId, out int type)
}
catch (Exception ex)
{
LogHelper.Error(ex.ToString(), "获取提取模板文件路径", "异常");
logger.LogError("获取提取模板文件路径" + ex.ToString());
type = 0;
return "";
}
......@@ -103,7 +103,7 @@ public string GetFilepath(int hospitalId, out int type)
public string ExtractData(int allotId, string mail, sys_hospital hospital, string firstPath)
{
LogHelper.Information($"开始执行绩效数据提取任务{new { allotId, mail, hospital }}", "提取绩效数据");
logger.LogInformation($"提取绩效数据开始执行绩效数据提取任务{new { allotId, mail, hospital }}");
List<PerSheet> sheetList = new List<PerSheet>();
string filepath = "";
try
......@@ -115,13 +115,13 @@ public string ExtractData(int allotId, string mail, sys_hospital hospital, strin
if (configList == null || !configList.Any())
{
LogHelper.Error("暂不支持自动提取绩效数据", "提取绩效数据");
logger.LogError("提取绩效数据 暂不支持自动提取绩效数据", "");
throw new PerformanceException($"暂不支持自动提取绩效数据");
}
if (scriptList == null || !scriptList.Any())
{
LogHelper.Error($"暂无该医院的配置信息和执行sql,无法进行数据提取", "提取绩效数据");
logger.LogError($"提取绩效数据 暂无该医院的配置信息和执行sql,无法进行数据提取", "");
throw new PerformanceException($"暂无该医院的配置信息和执行sql,无法进行数据提取");
}
......@@ -130,7 +130,7 @@ public string ExtractData(int allotId, string mail, sys_hospital hospital, strin
//判断是否是首次
if ((allotList == null || !allotList.Any(t => t.States > 0)) && (firstList != null || !firstList.Any()))
{
LogHelper.Information($"当前绩效为首次提取,从EXCEL中获取信息", "提取绩效数据");
logger.LogInformation($"提取绩效数据 当前绩效为首次提取,从EXCEL中获取信息", "");
//var first = firstList.OrderByDescending(t => t.CreateDate).FirstOrDefault();
//首次 从excel中获取人员信息,SHEET页信息,列头信息
sheetList = GetFileData(firstPath);
......@@ -138,7 +138,7 @@ public string ExtractData(int allotId, string mail, sys_hospital hospital, strin
}
else
{
LogHelper.Information($"当前绩效为非首次提取,从数据库中获取信息", "提取绩效数据");
logger.LogInformation($"提取绩效数据 当前绩效为非首次提取,从数据库中获取信息", "");
//非首次 从数据库中获取人员信息,SHEET页信息,列头信息
if (allotList.Any(t => t.Path != null && t.Path != ""))
{
......@@ -148,18 +148,18 @@ public string ExtractData(int allotId, string mail, sys_hospital hospital, strin
}
else
{
LogHelper.Error($"历史绩效未上传文件", "提取绩效数据");
logger.LogError($"提取绩效数据 历史绩效未上传文件", "");
throw new PerformanceException($"历史绩效未上传文件");
}
}
LogHelper.Information($"基础数据提取完成,", "提取绩效数据");
logger.LogInformation($"提取绩效数据 基础数据提取完成,", "");
var dpath = Path.Combine(environment.ContentRootPath, "Files", $"{hospital.ID}", "autoextract");
FileHelper.CreateDirectory(dpath);
string path = Path.Combine(dpath, $"绩效数据{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.xlsx");
//根据SHEET页信息,列头信息,创建EXCEL文件
if (WriteExcel(path, originalPath, sheetList, hospitalConfig, hospital.ID, allotList.First(t => t.ID == allotId), out filepath))
{
LogHelper.Information($"基础数据提取完成,文件保存成功{filepath}", "提取绩效数据");
logger.LogInformation($"提取绩效数据 基础数据提取完成,文件保存成功{filepath}", "");
//var allot = allotList.First(t => t.ID == allotId);
//allot.ExtractPath = filepath;
//if (!string.IsNullOrEmpty(filepath))
......@@ -170,14 +170,12 @@ public string ExtractData(int allotId, string mail, sys_hospital hospital, strin
}
catch (PerformanceException ex)
{
logger.LogError(ex.ToString());
LogHelper.Error(ex.ToString(), "提取绩效数据", "异常");
logger.LogError("提取绩效数据" + ex.ToString());
SendEmail(mail, "", $"{hospital.HosName}HIS数据提取失败", $"{hospital.HosName}提取数据失败,{ex.Message}!");
}
catch (Exception ex)
{
logger.LogError(ex.ToString());
LogHelper.Error(ex.ToString(), "提取绩效数据", "异常");
logger.LogError("提取绩效数据" + ex.ToString());
SendEmail(mail, "", $"{hospital.HosName}HIS数据提取失败", $"{hospital.HosName}提取数据过程中出现异常情况,我们将尽快解决问题。给您带来的不便我们深感歉意!");
}
finally
......@@ -225,10 +223,10 @@ private void SendEmail(string mail, string path, string subject, string body)
/// <param name="hospitalId"></param>
private bool WriteExcel(string newpath, string originalPath, List<PerSheet> sheetList, sys_hospitalconfig hospitalConfig, int hospitalId, per_allot allot, out string filepath)
{
LogHelper.Information($"开始向EXCEL中写入数据,", "提取绩效数据");
logger.LogInformation($"提取绩效数据 开始向EXCEL中写入数据,", "");
if (string.IsNullOrEmpty(originalPath))
{
LogHelper.Error($"{originalPath}文件路径无效", "提取绩效数据");
logger.LogError($"提取绩效数据{originalPath}文件路径无效", "");
throw new PerformanceException($"{originalPath}文件路径无效");
}
......@@ -246,7 +244,7 @@ private bool WriteExcel(string newpath, string originalPath, List<PerSheet> shee
if (importSheet == null) continue;
if (sheet.PerHeader == null) continue;
LogHelper.Information($"列头信息写入,", "提取绩效数据");
logger.LogInformation($"提取绩效数据列头信息写入,", "");
var maxHeaderRowNumber = sheet.PerHeader.Max(t => t.PointRow);
sheet.PerHeader?.ForEach(t =>
{
......@@ -277,7 +275,7 @@ private bool WriteExcel(string newpath, string originalPath, List<PerSheet> shee
//填充人员信息
if (SheetType.Employee == sheet.SheetType && sheet.PerData != null && sheet.PerData.Any())
{
LogHelper.Information($"填充人员信息,", "提取绩效数据");
logger.LogInformation($"提取绩效数据填充人员信息,", "");
var dataList = sheet.PerData.ConvertAll(new Converter<IPerData, PerDataEmployee>(t => (PerDataEmployee)t));
for (int i = 0; i < dataList.Count; i++)
{
......@@ -316,7 +314,7 @@ private bool WriteExcel(string newpath, string originalPath, List<PerSheet> shee
//临床科室医护绩效测算表
else if (SheetType.AccountBasic == sheet.SheetType && sheet.PerData != null && sheet.PerData.Any())
{
LogHelper.Information($"填充临床科室医护绩效测算表,", "提取绩效数据");
logger.LogInformation($"提取绩效数据 填充临床科室医护绩效测算表,", "");
var dataList = sheet.PerData.ConvertAll(new Converter<IPerData, PerDataAccountBaisc>(t => (PerDataAccountBaisc)t));
var children = new List<PerHeader>();
foreach (var item in sheet.PerHeader)
......@@ -362,12 +360,12 @@ private bool WriteExcel(string newpath, string originalPath, List<PerSheet> shee
//SHEET页在SQL提取中出现时,执行SQL脚本获得结果向EXCEL中填充
else if (scriptList.Any(t => sheet.SheetName.Contains(t.SheetName)))
{
LogHelper.Information($"执行SQL脚本获取数据,", "提取绩效数据");
logger.LogInformation($"提取绩效数据 执行SQL脚本获取数据,", "");
var script = scriptList.First(t => sheet.SheetName.Contains(t.SheetName));
if (!string.IsNullOrEmpty(script.ExecuteScript))
{
script.ExecuteScript = ReplaceParameter(script.ExecuteScript, allot);
LogHelper.Information($"SQL脚本{script.ExecuteScript},", "提取绩效数据");
logger.LogInformation($"提取绩效数据 SQL脚本{script.ExecuteScript},", "");
var children = new List<PerHeader>();
foreach (var item in sheet.PerHeader?.Select(t => t.Children))
{
......@@ -377,7 +375,7 @@ private bool WriteExcel(string newpath, string originalPath, List<PerSheet> shee
var connection = ConnectionBuilder.Create(DatabaseType.SqlServer, hospitalConfig.DbSource, hospitalConfig.DbName, hospitalConfig.DbUser, hospitalConfig.DbPassword);
var dataList = perforExtractRepository.ExecuteScript(connection, script.ExecuteScript, null);
LogHelper.Information($"写入SQL脚本执行结果", "提取绩效数据");
logger.LogInformation($"提取绩效数据 写入SQL脚本执行结果", "");
//用于查询核算单元
var deptList = dataList.Where(t => t.ColumnName == "科室名称").Select(t => t.Value.ToString()).Distinct().ToList();
......@@ -430,7 +428,7 @@ private bool WriteExcel(string newpath, string originalPath, List<PerSheet> shee
}
}
LogHelper.Information($"数据写入完成,开始保存文件{newpath}", "提取绩效数据");
logger.LogInformation($"提取绩效数据 数据写入完成,开始保存文件{newpath}", "");
file = new FileStream(newpath, FileMode.Create);
workbook.Write(file);
filepath = newpath;
......@@ -438,7 +436,7 @@ private bool WriteExcel(string newpath, string originalPath, List<PerSheet> shee
}
catch (Exception ex)
{
LogHelper.Error($"数据写入出现异常{ex.ToString()}", "提取绩效数据", "异常");
logger.LogError($"提取绩效数据 数据写入出现异常{ex.ToString()}");
throw ex;
}
finally
......
using Performance.DtoModels;
using Microsoft.Extensions.Logging;
using Performance.DtoModels;
using Performance.EntityModels;
using Performance.Infrastructure;
using Performance.Repository;
......@@ -12,6 +13,7 @@ namespace Performance.Services
{
public class ModExtractService : IAutoInjection
{
private readonly ILogger<ModExtractService> logger;
private PerforModextractRepository perforModextractRepository;
private PerforModitemRepository perforModitemRepository;
private PerforModmoduleRepository perforModmoduleRepository;
......@@ -20,14 +22,17 @@ public class ModExtractService : IAutoInjection
private PerforExtractRepository perforExtractRepository;
private PerforModdicRepository moddicRepository;
public ModExtractService(PerforModextractRepository perforModextractRepository,
PerforModitemRepository perforModitemRepository,
PerforModmoduleRepository perforModmoduleRepository,
PerforModspecialRepository perforModspecialRepository,
PerforHospitalconfigRepository perforHospitalconfigRepository,
PerforExtractRepository perforExtractRepository,
PerforModdicRepository moddicRepository)
public ModExtractService(
ILogger<ModExtractService> logger,
PerforModextractRepository perforModextractRepository,
PerforModitemRepository perforModitemRepository,
PerforModmoduleRepository perforModmoduleRepository,
PerforModspecialRepository perforModspecialRepository,
PerforHospitalconfigRepository perforHospitalconfigRepository,
PerforExtractRepository perforExtractRepository,
PerforModdicRepository moddicRepository)
{
this.logger = logger;
this.perforModextractRepository = perforModextractRepository;
this.perforModitemRepository = perforModitemRepository;
this.perforModmoduleRepository = perforModmoduleRepository;
......@@ -425,13 +430,13 @@ public void AddItems(int moduleId)
var sqlconfig = moddicRepository.GetEntity(w => w.HospitalId == module.HospitalId && w.Type.Trim().ToLower() == "itemsql");
if (sqlconfig == null)
{
LogHelper.Information("医院配置信息未设置", "添加默认收费项");
logger.LogInformation("{0} 医院配置信息未设置", "添加默认收费项");
throw new PerformanceException($"医院配置信息未设置");
}
var hospitalConfig = perforHospitalconfigRepository.GetEntity(t => t.HospitalId == module.HospitalId && t.Id == sqlconfig.ConfigId);
if (hospitalConfig == null)
{
LogHelper.Information("医院配置信息未设置", "添加默认收费项");
logger.LogInformation("{0} 医院配置信息未设置", "添加默认收费项");
throw new PerformanceException($"医院配置信息未设置");
}
......@@ -450,7 +455,7 @@ public void AddItems(int moduleId)
ExtractId = module.ExtractId,
ReadOnly = 1
});
LogHelper.Information($"受影响行数{itemList.Count()}", "添加默认收费项");
logger.LogInformation($"添加默认收费项 受影响行数{itemList.Count()}");
perforModitemRepository.AddRange(itemList.ToArray());
module.IsGenerated = 1;
perforModmoduleRepository.Update(module);
......
......@@ -165,14 +165,14 @@ public string ExtractData(int allotId, string email, int hospitalId)
workbook.Write(file);
}
logManageService.WriteMsg("提取绩效数据", $"{hospital.HosName}HIS数据提取成功,文件路径:{newPath}。", 5, allotId, "ReceiveMessage");
LogHelper.Information($"{hospital.HosName}HIS数据提取成功,文件路径:{newPath}。", "提取绩效数据");
logger.LogInformation($"提取绩效数据 {hospital.HosName}HIS数据提取成功,文件路径:{newPath}");
SendEmail(email, newPath, $"{hospital.HosName}HIS数据提取成功", $"{hospital.HosName}{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}成功提取。");
return newPath;
}
catch (Exception ex)
{
logManageService.WriteMsg("提取数据异常", $"数据写入出现异常", 4, allotId, "ReceiveMessage");
LogHelper.Error($"数据写入出现异常{ex.ToString()}", "提取绩效数据", "异常");
logger.LogError($"提取绩效数据异常 数据写入出现异常{ex.ToString()}");
SendEmail(email, "", $"{hospital.HosName}HIS数据提取失败", $"{hospital.HosName}提取数据过程中出现异常情况,我们将尽快解决问题。给您带来的不便我们深感歉意!");
throw ex;
}
......@@ -229,7 +229,7 @@ private void WriteOtherIncome(ISheet sheet, int hospitalId, List<AccountUnitEnti
int cellStartIndex = sheetRead.Point.HeaderFirstCellNum.Value + 4;
logManageService.WriteMsg("提取绩效数据", $"写入列头信息 -- {module.ModuleName}", 1, AllotId, "ReceiveMessage");
LogHelper.Information($"写入列头信息 -- {module.ModuleName}", "提取绩效数据");
logger.LogInformation($"提取绩效数据 写入列头信息 -- {module.ModuleName}");
//写入列头信息
foreach (var item in itemList)
{
......@@ -264,7 +264,7 @@ private void WriteOtherIncome(ISheet sheet, int hospitalId, List<AccountUnitEnti
foreach (var moditem in category)
{
logManageService.WriteMsg("提取绩效数据", $"执行SQL脚本获取数据 -- {module.ModuleName}", 1, AllotId, "ReceiveMessage");
LogHelper.Information($"执行SQL脚本获取数据 -- {module.ModuleName},", "提取绩效数据");
logger.LogInformation($"提取绩效数据 执行SQL脚本获取数据 -- {module.ModuleName}");
var config = hospitalConfigList.FirstOrDefault(t => t.Id == moditem.ConfigId);
if (config == null) continue;
......@@ -282,7 +282,7 @@ private void WriteOtherIncome(ISheet sheet, int hospitalId, List<AccountUnitEnti
}
logManageService.WriteMsg("提取绩效数据", $"填充数据 -- {module.ModuleName}", 1, AllotId, "ReceiveMessage");
LogHelper.Information($"填充数据 -- {module.ModuleName}", "提取绩效数据");
logger.LogInformation($"提取绩效数据 填充数据 -- {module.ModuleName}");
//写入数据
var rowIndex = sheetRead.Point.HeaderFirstRowNum.Value + 1;
foreach (var department in allExtract.Select(t => t.Department).Distinct())
......@@ -342,7 +342,7 @@ private void WriteIncome(ISheet sheet, int hospitalId, List<AccountUnitEntity> u
var head = GetOrCreate(sheet, sheetRead.Point.HeaderFirstRowNum.Value);
logManageService.WriteMsg("提取绩效数据", $"写入列头信息 -- {module.ModuleName}", 1, AllotId, "ReceiveMessage");
LogHelper.Information($"写入列头信息 -- {module.ModuleName}", "提取绩效数据");
logger.LogInformation($"提取绩效数据 写入列头信息 -- {module.ModuleName}");
//写入列头信息
int cellStartIndex = sheetRead.Point.HeaderFirstCellNum.Value + 4;
foreach (var item in itemList)
......@@ -372,7 +372,7 @@ private void WriteIncome(ISheet sheet, int hospitalId, List<AccountUnitEntity> u
foreach (var item in extractList)
{
logManageService.WriteMsg("提取绩效数据", $"执行SQL脚本获取数据 -- {module.ModuleName}", 1, AllotId, "ReceiveMessage");
LogHelper.Information($"执行SQL脚本获取数据 -- {module.ModuleName}", "提取绩效数据");
logger.LogInformation($"提取绩效数据 执行SQL脚本获取数据 -- {module.ModuleName}");
var config = hospitalConfigList.FirstOrDefault(t => t.Id == module.ConfigId);
if (config == null) continue;
......@@ -382,7 +382,7 @@ private void WriteIncome(ISheet sheet, int hospitalId, List<AccountUnitEntity> u
}
logManageService.WriteMsg("提取绩效数据", $"填充数据 -- {module.ModuleName}", 1, AllotId, "ReceiveMessage");
LogHelper.Information($"填充数据 -- {module.ModuleName}", "提取绩效数据");
logger.LogInformation($"提取绩效数据 填充数据 -- {module.ModuleName}");
//写入数据
var rowIndex = sheetRead.Point.HeaderFirstRowNum.Value + 1;
foreach (var department in allExtract.Select(t => t.Department).Distinct())
......@@ -471,7 +471,7 @@ private void WriteWorkload(ISheet sheet, int hospitalId, List<AccountUnitEntity>
var factor = GetOrCreate(sheet, sheetRead.Point.HeaderFirstRowNum.Value + 1);
logManageService.WriteMsg("提取绩效数据", $"写入列头信息 -- {module.ModuleName}", 1, AllotId, "ReceiveMessage");
LogHelper.Information($"写入列头信息 -- {module.ModuleName}", "提取绩效数据");
logger.LogInformation($"提取绩效数据 写入列头信息 -- {module.ModuleName}");
//写入列头信息
int cellStartIndex = sheetRead.Point.HeaderFirstCellNum.Value + 2;
foreach (var item in itemList)
......@@ -498,7 +498,7 @@ private void WriteWorkload(ISheet sheet, int hospitalId, List<AccountUnitEntity>
foreach (var moditem in category)
{
logManageService.WriteMsg("提取绩效数据", $"执行SQL脚本获取数据 -- {module.ModuleName}", 1, AllotId, "ReceiveMessage");
LogHelper.Information($"执行SQL脚本获取数据 -- {module.ModuleName},", "提取绩效数据");
logger.LogInformation($"提取绩效数据 执行SQL脚本获取数据 -- {module.ModuleName}");
var config = hospitalConfigList.FirstOrDefault(t => t.Id == moditem.ConfigId);
if (config == null) continue;
......@@ -516,7 +516,7 @@ private void WriteWorkload(ISheet sheet, int hospitalId, List<AccountUnitEntity>
}
logManageService.WriteMsg("提取绩效数据", $"填充数据 -- {module.ModuleName}", 1, AllotId, "ReceiveMessage");
LogHelper.Information($"填充数据 -- {module.ModuleName}", "提取绩效数据");
logger.LogInformation($"提取绩效数据 填充数据 -- {module.ModuleName}");
//写入数据
var rowIndex = sheetRead.Point.HeaderFirstRowNum.Value + 2;
foreach (var department in allExtract.Select(t => t.Department).Distinct())
......@@ -563,7 +563,7 @@ private List<ExtractDto> QueryDatabase(sys_hospitalconfig config, mod_extract ex
executeScript = Regex.Replace(executeScript, item.Key, item.Value, RegexOptions.IgnoreCase);
}
//logManageService.WriteMsg("提取绩效数据", $"SQL脚本:{executeScript}", 1, AllotId, "ReceiveMessage");
LogHelper.Information($"SQL脚本{executeScript},", "提取绩效数据");
logger.LogInformation($"提取绩效数据 SQL脚本{executeScript}");
var result = connection.Query<ExtractDto>(executeScript, commandTimeout: 20000);
if (result != null && result.Count() > 0)
{
......@@ -594,7 +594,7 @@ private void WriteExpend(ISheet sheet, int hospitalId, IPerSheetDataRead sheetRe
int cellStartIndex = sheetRead.Point.HeaderFirstCellNum.Value + 4;
logManageService.WriteMsg("提取绩效数据", $"写入列头信息 -- {module.ModuleName}", 1, AllotId, "ReceiveMessage");
LogHelper.Information($"写入列头信息 -- {module.ModuleName}", "提取绩效数据");
logger.LogInformation($"提取绩效数据 写入列头信息 -- {module.ModuleName}");
//写入列头信息
foreach (var item in itemList)
{
......@@ -649,7 +649,7 @@ private void WriteEmployee(ISheet sheet, int allotLastId, IPerSheetDataRead shee
};
logManageService.WriteMsg("提取绩效数据", $"填充数据 -- 人员信息", 1, AllotId, "ReceiveMessage");
LogHelper.Information($"填充数据 -- 人员信息", "提取绩效数据");
logger.LogInformation($"提取绩效数据 填充数据 -- 人员信息");
var dataList = perforImemployeeRepository.GetEntities(t => t.AllotID == allotLastId)?.OrderBy(t => t.AccountType).ToList();
for (int i = 0; i < dataList.Count; i++)
{
......@@ -701,7 +701,7 @@ private void WriteSpecialUnit(ISheet sheet, int hospitalId, per_allot allot, IPe
foreach (var moditem in category)
{
logManageService.WriteMsg("提取绩效数据", $"执行SQL脚本获取数据 -- 特殊核算单元绩效测算表", 1, AllotId, "ReceiveMessage");
LogHelper.Information($"执行SQL脚本获取数据 -- 特殊核算单元绩效测算表,", "提取绩效数据");
logger.LogInformation($"提取绩效数据 执行SQL脚本获取数据 -- 特殊核算单元绩效测算表,");
var config = hospitalConfigList.FirstOrDefault(t => t.Id == moditem.ConfigId);
if (config == null) continue;
......@@ -730,7 +730,7 @@ private void WriteSpecialUnit(ISheet sheet, int hospitalId, per_allot allot, IPe
int mergedEnd = sheetRead.Point.DataFirstRowNum.Value;
logManageService.WriteMsg("提取绩效数据", $"填充数据 -- 特殊核算单元绩效测算表", 1, AllotId, "ReceiveMessage");
LogHelper.Information($"填充数据 -- 特殊核算单元绩效测算表", "提取绩效数据");
logger.LogInformation($"提取绩效数据 填充数据 -- 特殊核算单元绩效测算表");
for (int i = 0; i < modDataList.Count; i++)
{
var headIndex = sheetRead.Point.HeaderFirstRowNum;
......@@ -798,7 +798,7 @@ private void WriteAccountBasic(ISheet sheet, int allotLastId, IPerSheetDataRead
};
logManageService.WriteMsg("提取绩效数据", $"填充数据 -- 临床科室医护绩效测算表", 1, AllotId, "ReceiveMessage");
LogHelper.Information($"填充数据 -- 临床科室医护绩效测算表", "提取绩效数据");
logger.LogInformation($"提取绩效数据 填充数据 -- 临床科室医护绩效测算表");
var dataList = perforImaccountbasicRepository.GetEntities(t => t.AllotID == allotLastId)?.OrderBy(t => t.UnitType).ThenBy(t => t.DoctorAccountingUnit).ToList();
for (int i = 0; i < dataList.Count; i++)
{
......@@ -926,12 +926,12 @@ public string Judge(int allotId, int hospitalId, int useTemplate)
}
catch (PerformanceException ex)
{
LogHelper.Error(ex.ToString(), "提取绩效数据");
logger.LogError($"提取绩效数据异常 {ex.ToString()}");
result = ex.Message;
}
catch (Exception ex)
{
LogHelper.Error(ex.ToString(), "提取绩效数据");
logger.LogError($"提取绩效数据异常 {ex.ToString()}");
throw new Exception(ex.Message);
}
return result;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment