Skip to content

Commit 1ec95ee

Browse files
committed
✨ 统一使用Serilog,移除本地写LOG代码
Close #370
1 parent e41f963 commit 1ec95ee

File tree

11 files changed

+745
-1455
lines changed

11 files changed

+745
-1455
lines changed

Blog.Core.Api/Controllers/MonitorController.cs

Lines changed: 95 additions & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,13 @@ public class MonitorController : BaseApiController
2626
private readonly IApplicationUserServices _applicationUserServices;
2727
private readonly ILogger<MonitorController> _logger;
2828

29-
public MonitorController(IHubContext<ChatHub> hubContext, IWebHostEnvironment env, IApplicationUserServices applicationUserServices, ILogger<MonitorController> logger)
29+
public MonitorController(IHubContext<ChatHub> hubContext, IWebHostEnvironment env,
30+
IApplicationUserServices applicationUserServices, ILogger<MonitorController> logger)
3031
{
31-
_hubContext = hubContext;
32-
_env = env;
32+
_hubContext = hubContext;
33+
_env = env;
3334
_applicationUserServices = applicationUserServices;
34-
_logger = logger;
35+
_logger = logger;
3536
}
3637

3738
/// <summary>
@@ -43,13 +44,13 @@ public MessageModel<ServerViewModel> Server()
4344
{
4445
return Success(new ServerViewModel()
4546
{
46-
EnvironmentName = _env.EnvironmentName,
47-
OSArchitecture = RuntimeInformation.OSArchitecture.ObjToString(),
48-
ContentRootPath = _env.ContentRootPath,
49-
WebRootPath = _env.WebRootPath,
47+
EnvironmentName = _env.EnvironmentName,
48+
OSArchitecture = RuntimeInformation.OSArchitecture.ObjToString(),
49+
ContentRootPath = _env.ContentRootPath,
50+
WebRootPath = _env.WebRootPath,
5051
FrameworkDescription = RuntimeInformation.FrameworkDescription,
51-
MemoryFootprint = (Process.GetCurrentProcess().WorkingSet64 / 1048576).ToString("N2") + " MB",
52-
WorkingTime = DateHelper.TimeSubTract(DateTime.Now, Process.GetCurrentProcess().StartTime)
52+
MemoryFootprint = (Process.GetCurrentProcess().WorkingSet64 / 1048576).ToString("N2") + " MB",
53+
WorkingTime = DateHelper.TimeSubTract(DateTime.Now, Process.GetCurrentProcess().StartTime)
5354
}, "获取服务器配置信息成功");
5455
}
5556

@@ -64,17 +65,18 @@ public MessageModel<List<LogInfo>> Get()
6465
{
6566
if (AppSettings.app(new string[] { "Middleware", "SignalRSendLog", "Enabled" }).ObjToBool())
6667
{
67-
_hubContext.Clients.All.SendAsync("ReceiveUpdate", LogLock.GetLogData()).Wait();
68+
_hubContext.Clients.All.SendAsync("ReceiveUpdate", "执行成功").Wait();
6869
}
70+
6971
return Success<List<LogInfo>>(null, "执行成功");
7072
}
7173

7274

73-
7475
[HttpGet]
7576
public MessageModel<RequestApiWeekView> GetRequestApiinfoByWeek()
7677
{
77-
return Success(LogLock.RequestApiinfoByWeek(), "成功");
78+
//后续补充扩展Log
79+
return Success(new RequestApiWeekView(), "成功");
7880
}
7981

8082
[HttpGet]
@@ -87,7 +89,8 @@ public MessageModel<AccessApiDateView> GetAccessApiByDate()
8789
// response = LogLock.AccessApiByDate()
8890
//};
8991

90-
return Success(LogLock.AccessApiByDate(), "获取成功");
92+
//后续补充扩展Log
93+
return Success(new AccessApiDateView(), "获取成功");
9194
}
9295

9396
[HttpGet]
@@ -100,70 +103,74 @@ public MessageModel<AccessApiDateView> GetAccessApiByHour()
100103
// response = LogLock.AccessApiByHour()
101104
//};
102105

103-
return Success(LogLock.AccessApiByHour(), "获取成功");
106+
//后续补充扩展Log
107+
return Success(new AccessApiDateView(), "获取成功");
104108
}
105109

106110
private List<UserAccessModel> GetAccessLogsToday(IWebHostEnvironment environment)
107111
{
108112
List<UserAccessModel> userAccessModels = new();
109-
var accessLogs = LogLock.ReadLog(
110-
Path.Combine(environment.ContentRootPath, "Log"), "RecordAccessLogs_", Encoding.UTF8, ReadType.PrefixLatest
111-
).ObjToString();
112-
try
113-
{
114-
return JsonConvert.DeserializeObject<List<UserAccessModel>>("[" + accessLogs + "]");
115-
}
116-
catch (Exception)
117-
{
118-
var accLogArr = accessLogs.Split("\n");
119-
foreach (var item in accLogArr)
120-
{
121-
if (item.ObjToString() != "")
122-
{
123-
try
124-
{
125-
var accItem = JsonConvert.DeserializeObject<UserAccessModel>(item.TrimEnd(','));
126-
userAccessModels.Add(accItem);
127-
}
128-
catch (Exception)
129-
{
130-
}
131-
}
132-
}
133-
134-
}
113+
//后续补充扩展Log
114+
// var accessLogs = LogLock.ReadLog(
115+
// Path.Combine(environment.ContentRootPath, "Log"), "RecordAccessLogs_", Encoding.UTF8,
116+
// ReadType.PrefixLatest
117+
// ).ObjToString();
118+
// try
119+
// {
120+
// return JsonConvert.DeserializeObject<List<UserAccessModel>>("[" + accessLogs + "]");
121+
// }
122+
// catch (Exception)
123+
// {
124+
// var accLogArr = accessLogs.Split("\n");
125+
// foreach (var item in accLogArr)
126+
// {
127+
// if (item.ObjToString() != "")
128+
// {
129+
// try
130+
// {
131+
// var accItem = JsonConvert.DeserializeObject<UserAccessModel>(item.TrimEnd(','));
132+
// userAccessModels.Add(accItem);
133+
// }
134+
// catch (Exception)
135+
// {
136+
// }
137+
// }
138+
// }
139+
// }
135140

136141
return userAccessModels;
137142
}
143+
138144
private List<ActiveUserVM> GetAccessLogsTrend(IWebHostEnvironment environment)
139145
{
140146
List<ActiveUserVM> userAccessModels = new();
141-
var accessLogs = LogLock.ReadLog(
142-
Path.Combine(environment.ContentRootPath, "Log"), "ACCESSTRENDLOG_", Encoding.UTF8, ReadType.PrefixLatest
143-
).ObjToString();
144-
try
145-
{
146-
return JsonConvert.DeserializeObject<List<ActiveUserVM>>(accessLogs);
147-
}
148-
catch (Exception)
149-
{
150-
var accLogArr = accessLogs.Split("\n");
151-
foreach (var item in accLogArr)
152-
{
153-
if (item.ObjToString() != "")
154-
{
155-
try
156-
{
157-
var accItem = JsonConvert.DeserializeObject<ActiveUserVM>(item.TrimStart('[').TrimEnd(']'));
158-
userAccessModels.Add(accItem);
159-
}
160-
catch (Exception)
161-
{
162-
}
163-
}
164-
}
165-
166-
}
147+
//后续补充扩展Log
148+
// var accessLogs = LogLock.ReadLog(
149+
// Path.Combine(environment.ContentRootPath, "Log"), "ACCESSTRENDLOG_", Encoding.UTF8,
150+
// ReadType.PrefixLatest
151+
// ).ObjToString();
152+
// try
153+
// {
154+
// return JsonConvert.DeserializeObject<List<ActiveUserVM>>(accessLogs);
155+
// }
156+
// catch (Exception)
157+
// {
158+
// var accLogArr = accessLogs.Split("\n");
159+
// foreach (var item in accLogArr)
160+
// {
161+
// if (item.ObjToString() != "")
162+
// {
163+
// try
164+
// {
165+
// var accItem = JsonConvert.DeserializeObject<ActiveUserVM>(item.TrimStart('[').TrimEnd(']'));
166+
// userAccessModels.Add(accItem);
167+
// }
168+
// catch (Exception)
169+
// {
170+
// }
171+
// }
172+
// }
173+
// }
167174

168175
return userAccessModels;
169176
}
@@ -175,17 +182,16 @@ public MessageModel<WelcomeInitData> GetActiveUsers([FromServices] IWebHostEnvir
175182

176183
var Logs = accessLogsToday.OrderByDescending(d => d.BeginTime).Take(50).ToList();
177184

178-
var errorCountToday = LogLock.GetLogData().Where(d => d.Import == 9).Count();
179-
180185
accessLogsToday = accessLogsToday.Where(d => d.User != "").ToList();
181186

182187
var activeUsers = (from n in accessLogsToday
183-
group n by new { n.User } into g
184-
select new ActiveUserVM
185-
{
186-
user = g.Key.User,
187-
count = g.Count(),
188-
}).ToList();
188+
group n by new { n.User }
189+
into g
190+
select new ActiveUserVM
191+
{
192+
user = g.Key.User,
193+
count = g.Count(),
194+
}).ToList();
189195

190196
int activeUsersCount = activeUsers.Count;
191197
activeUsers = activeUsers.OrderByDescending(d => d.count).Take(10).ToList();
@@ -206,11 +212,11 @@ public MessageModel<WelcomeInitData> GetActiveUsers([FromServices] IWebHostEnvir
206212

207213
return Success(new WelcomeInitData()
208214
{
209-
activeUsers = activeUsers,
215+
activeUsers = activeUsers,
210216
activeUserCount = activeUsersCount,
211-
errorCount = errorCountToday,
212-
logs = Logs,
213-
activeCount = GetAccessLogsTrend(environment)
217+
errorCount = default,
218+
logs = Logs,
219+
activeCount = GetAccessLogsTrend(environment)
214220
}, "获取成功");
215221
}
216222

@@ -224,12 +230,13 @@ public async Task<MessageModel<AccessApiDateView>> GetIds4Users()
224230
var users = await _applicationUserServices.Query(d => d.tdIsDelete == false);
225231

226232
apiDates = (from n in users
227-
group n by new { n.birth.Date } into g
228-
select new ApiDate
229-
{
230-
date = g.Key?.Date.ToString("yyyy-MM-dd"),
231-
count = g.Count(),
232-
}).ToList();
233+
group n by new { n.birth.Date }
234+
into g
235+
select new ApiDate
236+
{
237+
date = g.Key?.Date.ToString("yyyy-MM-dd"),
238+
count = g.Count(),
239+
}).ToList();
233240

234241
apiDates = apiDates.OrderByDescending(d => d.date).Take(30).ToList();
235242
}
@@ -239,7 +246,7 @@ public async Task<MessageModel<AccessApiDateView>> GetIds4Users()
239246
{
240247
apiDates.Add(new ApiDate()
241248
{
242-
date = "没数据,或未开启相应接口服务",
249+
date = "没数据,或未开启相应接口服务",
243250
count = 0
244251
});
245252
}
@@ -257,10 +264,9 @@ public async Task<MessageModel<AccessApiDateView>> GetIds4Users()
257264
return Success(new AccessApiDateView
258265
{
259266
columns = new string[] { "date", "count" },
260-
rows = apiDates.OrderBy(d => d.date).ToList(),
267+
rows = apiDates.OrderBy(d => d.date).ToList(),
261268
}, "获取成功");
262269
}
263-
264270
}
265271

266272
public class WelcomeInitData
@@ -271,5 +277,4 @@ public class WelcomeInitData
271277
public int errorCount { get; set; }
272278
public List<ActiveUserVM> activeCount { get; set; }
273279
}
274-
275-
}
280+
}

Blog.Core.Api/Filter/GlobalExceptionFilter.cs

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -19,19 +19,20 @@ public class GlobalExceptionsFilter : IExceptionFilter
1919
private readonly IHubContext<ChatHub> _hubContext;
2020
private readonly ILogger<GlobalExceptionsFilter> _loggerHelper;
2121

22-
public GlobalExceptionsFilter(IWebHostEnvironment env, ILogger<GlobalExceptionsFilter> loggerHelper, IHubContext<ChatHub> hubContext)
22+
public GlobalExceptionsFilter(IWebHostEnvironment env, ILogger<GlobalExceptionsFilter> loggerHelper,
23+
IHubContext<ChatHub> hubContext)
2324
{
24-
_env = env;
25+
_env = env;
2526
_loggerHelper = loggerHelper;
26-
_hubContext = hubContext;
27+
_hubContext = hubContext;
2728
}
2829

2930
public void OnException(ExceptionContext context)
3031
{
3132
var json = new MessageModel<string>();
3233

33-
json.msg = context.Exception.Message;//错误信息
34-
json.status = 500;//500异常
34+
json.msg = context.Exception.Message; //错误信息
35+
json.status = 500; //500异常
3536
var errorAudit = "Unable to resolve service for";
3637
if (!string.IsNullOrEmpty(json.msg) && json.msg.Contains(errorAudit))
3738
{
@@ -40,8 +41,9 @@ public void OnException(ExceptionContext context)
4041

4142
if (_env.EnvironmentName.ObjToString().Equals("Development"))
4243
{
43-
json.msgDev = context.Exception.StackTrace;//堆栈信息
44+
json.msgDev = context.Exception.StackTrace; //堆栈信息
4445
}
46+
4547
var res = new ContentResult();
4648
res.Content = JsonHelper.GetJSON<MessageModel<string>>(json);
4749

@@ -54,10 +56,8 @@ public void OnException(ExceptionContext context)
5456
_loggerHelper.LogError(json.msg + WriteLog(json.msg, context.Exception));
5557
if (AppSettings.app(new string[] { "Middleware", "SignalRSendLog", "Enabled" }).ObjToBool())
5658
{
57-
_hubContext.Clients.All.SendAsync("ReceiveUpdate", LogLock.GetLogData()).Wait();
59+
_hubContext.Clients.All.SendAsync("ReceiveUpdate", json.msg).Wait();
5860
}
59-
60-
6161
}
6262

6363
/// <summary>
@@ -68,29 +68,33 @@ public void OnException(ExceptionContext context)
6868
/// <returns></returns>
6969
public string WriteLog(string throwMsg, Exception ex)
7070
{
71-
return string.Format("\r\n【自定义错误】:{0} \r\n【异常类型】:{1} \r\n【异常信息】:{2} \r\n【堆栈调用】:{3}", new object[] { throwMsg,
72-
ex.GetType().Name, ex.Message, ex.StackTrace });
71+
return string.Format("\r\n【自定义错误】:{0} \r\n【异常类型】:{1} \r\n【异常信息】:{2} \r\n【堆栈调用】:{3}", new object[]
72+
{
73+
throwMsg,
74+
ex.GetType().Name, ex.Message, ex.StackTrace
75+
});
7376
}
74-
7577
}
78+
7679
public class InternalServerErrorObjectResult : ObjectResult
7780
{
7881
public InternalServerErrorObjectResult(object value) : base(value)
7982
{
8083
StatusCode = StatusCodes.Status500InternalServerError;
8184
}
8285
}
86+
8387
//返回错误信息
8488
public class JsonErrorResponse
8589
{
8690
/// <summary>
8791
/// 生产环境的消息
8892
/// </summary>
8993
public string Message { get; set; }
94+
9095
/// <summary>
9196
/// 开发环境的消息
9297
/// </summary>
9398
public string DevelopmentMessage { get; set; }
9499
}
95-
96-
}
100+
}

Blog.Core.Common/Hubs/ChatHub.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,10 +96,10 @@ public async Task SendMessage(string user, string message)
9696
public async Task GetLatestCount(string random)
9797
{
9898
//2、服务端主动向客户端发送数据,名字千万不能错
99-
if (AppSettings.app(new string[] {"Middleware", "SignalRSendLog", "Enabled"}).ObjToBool())
99+
if (AppSettings.app(new string[] { "Middleware", "SignalRSendLog", "Enabled" }).ObjToBool())
100100
{
101101
//TODO 主动发送错误消息
102-
await Clients.All.ReceiveUpdate(LogLock.GetLogData());
102+
await Clients.All.ReceiveUpdate("这是一个LOG");
103103
}
104104

105105

0 commit comments

Comments
 (0)