forked from anjoy8/Blog.Core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMonitorController.cs
More file actions
282 lines (247 loc) · 9.8 KB
/
MonitorController.cs
File metadata and controls
282 lines (247 loc) · 9.8 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
using Blog.Core.Common;
using Blog.Core.Common.Helper;
using Blog.Core.Common.LogHelper;
using Blog.Core.Hubs;
using Blog.Core.IServices;
using Blog.Core.Model;
using Blog.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Blog.Core.Extensions.Middlewares;
namespace Blog.Core.Controllers
{
[Route("api/[Controller]/[action]")]
[ApiController]
[AllowAnonymous]
public class MonitorController : BaseApiController
{
private readonly IHubContext<ChatHub> _hubContext;
private readonly IWebHostEnvironment _env;
private readonly IApplicationUserServices _applicationUserServices;
private readonly ILogger<MonitorController> _logger;
public MonitorController(IHubContext<ChatHub> hubContext, IWebHostEnvironment env, IApplicationUserServices applicationUserServices, ILogger<MonitorController> logger)
{
_hubContext = hubContext;
_env = env;
_applicationUserServices = applicationUserServices;
_logger = logger;
}
/// <summary>
/// 服务器配置信息
/// </summary>
/// <returns></returns>
[HttpGet]
public MessageModel<ServerViewModel> Server()
{
return Success(new ServerViewModel()
{
EnvironmentName = _env.EnvironmentName,
OSArchitecture = RuntimeInformation.OSArchitecture.ObjToString(),
ContentRootPath = _env.ContentRootPath,
WebRootPath = _env.WebRootPath,
FrameworkDescription = RuntimeInformation.FrameworkDescription,
MemoryFootprint = (Process.GetCurrentProcess().WorkingSet64 / 1048576).ToString("N2") + " MB",
WorkingTime = DateHelper.TimeSubTract(DateTime.Now, Process.GetCurrentProcess().StartTime)
}, "获取服务器配置信息成功");
}
/// <summary>
/// SignalR send data
/// </summary>
/// <returns></returns>
// GET: api/Logs
[HttpGet]
public MessageModel<List<LogInfo>> Get()
{
if (AppSettings.app(new string[] { "Middleware", "SignalRSendLog", "Enabled" }).ObjToBool())
{
_hubContext.Clients.All.SendAsync("ReceiveUpdate", LogLock.GetLogData()).Wait();
}
return Success<List<LogInfo>>(null, "执行成功");
}
[HttpGet]
public MessageModel<RequestApiWeekView> GetRequestApiinfoByWeek()
{
return Success(LogLock.RequestApiinfoByWeek(), "成功");
}
[HttpGet]
public MessageModel<AccessApiDateView> GetAccessApiByDate()
{
//return new MessageModel<AccessApiDateView>()
//{
// msg = "获取成功",
// success = true,
// response = LogLock.AccessApiByDate()
//};
return Success(LogLock.AccessApiByDate(), "获取成功");
}
[HttpGet]
public MessageModel<AccessApiDateView> GetAccessApiByHour()
{
//return new MessageModel<AccessApiDateView>()
//{
// msg = "获取成功",
// success = true,
// response = LogLock.AccessApiByHour()
//};
return Success(LogLock.AccessApiByHour(), "获取成功");
}
private List<UserAccessModel> GetAccessLogsToday(IWebHostEnvironment environment)
{
List<UserAccessModel> userAccessModels = new();
var accessLogs = LogLock.ReadLog(
Path.Combine(environment.ContentRootPath, "Log"), "RecordAccessLogs_", Encoding.UTF8, ReadType.PrefixLatest
).ObjToString();
try
{
return JsonConvert.DeserializeObject<List<UserAccessModel>>("[" + accessLogs + "]");
}
catch (Exception)
{
var accLogArr = accessLogs.Split("\n");
foreach (var item in accLogArr)
{
if (item.ObjToString() != "")
{
try
{
var accItem = JsonConvert.DeserializeObject<UserAccessModel>(item.TrimEnd(','));
userAccessModels.Add(accItem);
}
catch (Exception)
{
}
}
}
}
return userAccessModels;
}
private List<ActiveUserVM> GetAccessLogsTrend(IWebHostEnvironment environment)
{
List<ActiveUserVM> userAccessModels = new();
var accessLogs = LogLock.ReadLog(
Path.Combine(environment.ContentRootPath, "Log"), "ACCESSTRENDLOG_", Encoding.UTF8, ReadType.PrefixLatest
).ObjToString();
try
{
return JsonConvert.DeserializeObject<List<ActiveUserVM>>(accessLogs);
}
catch (Exception)
{
var accLogArr = accessLogs.Split("\n");
foreach (var item in accLogArr)
{
if (item.ObjToString() != "")
{
try
{
var accItem = JsonConvert.DeserializeObject<ActiveUserVM>(item.TrimStart('[').TrimEnd(']'));
userAccessModels.Add(accItem);
}
catch (Exception)
{
}
}
}
}
return userAccessModels;
}
[HttpGet]
public MessageModel<WelcomeInitData> GetActiveUsers([FromServices] IWebHostEnvironment environment)
{
var accessLogsToday = GetAccessLogsToday(environment).Where(d => d.BeginTime.ObjToDate() >= DateTime.Today);
var Logs = accessLogsToday.OrderByDescending(d => d.BeginTime).Take(50).ToList();
var errorCountToday = LogLock.GetLogData().Where(d => d.Import == 9).Count();
accessLogsToday = accessLogsToday.Where(d => d.User != "").ToList();
var activeUsers = (from n in accessLogsToday
group n by new { n.User } into g
select new ActiveUserVM
{
user = g.Key.User,
count = g.Count(),
}).ToList();
int activeUsersCount = activeUsers.Count;
activeUsers = activeUsers.OrderByDescending(d => d.count).Take(10).ToList();
//return new MessageModel<WelcomeInitData>()
//{
// msg = "获取成功",
// success = true,
// response = new WelcomeInitData()
// {
// activeUsers = activeUsers,
// activeUserCount = activeUsersCount,
// errorCount = errorCountToday,
// logs = Logs,
// activeCount = GetAccessLogsTrend(environment)
// }
//};
return Success(new WelcomeInitData()
{
activeUsers = activeUsers,
activeUserCount = activeUsersCount,
errorCount = errorCountToday,
logs = Logs,
activeCount = GetAccessLogsTrend(environment)
}, "获取成功");
}
[HttpGet]
public async Task<MessageModel<AccessApiDateView>> GetIds4Users()
{
List<ApiDate> apiDates = new List<ApiDate>();
if (AppSettings.app(new string[] { "MutiDBEnabled" }).ObjToBool())
{
var users = await _applicationUserServices.Query(d => d.tdIsDelete == false);
apiDates = (from n in users
group n by new { n.birth.Date } into g
select new ApiDate
{
date = g.Key?.Date.ToString("yyyy-MM-dd"),
count = g.Count(),
}).ToList();
apiDates = apiDates.OrderByDescending(d => d.date).Take(30).ToList();
}
if (apiDates.Count == 0)
{
apiDates.Add(new ApiDate()
{
date = "没数据,或未开启相应接口服务",
count = 0
});
}
//return new MessageModel<AccessApiDateView>()
//{
// msg = "获取成功",
// success = true,
// response = new AccessApiDateView
// {
// columns = new string[] { "date", "count" },
// rows = apiDates.OrderBy(d => d.date).ToList(),
// }
//};
return Success(new AccessApiDateView
{
columns = new string[] { "date", "count" },
rows = apiDates.OrderBy(d => d.date).ToList(),
}, "获取成功");
}
}
public class WelcomeInitData
{
public List<ActiveUserVM> activeUsers { get; set; }
public int activeUserCount { get; set; }
public List<UserAccessModel> logs { get; set; }
public int errorCount { get; set; }
public List<ActiveUserVM> activeCount { get; set; }
}
}