using Dpz.Core.Public.ViewModel.AppLogs;
using Seq.Api;
using Seq.Api.Model.Events;
namespace Dpz.Core.Service.RepositoryServiceImpl;
public class AppLogEntryService(
IConfiguration configuration,
ILogger<AppLogEntryService> logger)
: IAppLogEntryService
{
private SeqConnection GetSeqConnection()
{
var logApiHost = configuration["LogApiHost"];
if (string.IsNullOrEmpty(logApiHost))
throw new Exception("configuration no LogApiHost node");
var apiKey = configuration["LogSeq:ApiKey"];
if (string.IsNullOrEmpty(apiKey))
throw new Exception("configuration no LogSeq.Apikey node");
var connection = configuration["AgileConfig:env"] != "PROD"
? new SeqConnection(logApiHost, configuration["LogApiKey"])
: new SeqConnection(logApiHost, apiKey);
return connection;
}
public async Task<ResultSetPart?> GetPageAsync(string? filter = null, string? startAtId = null,
string? afterId = null, int pageSize = 20)
{
using var connection = GetSeqConnection();
var part = await connection.Events.PageAsync(
filter: filter,
startAtId: startAtId,
afterId: afterId,
render: true,
count: pageSize);
return part;
}
public async Task<List<AccessSummary>> GetLatestAccessNumberAsync(int? days)
{
var startDate = days == null
? DateTime.Now.Date.AddHours(8)
: DateTime.Now.Date.AddHours(8).AddDays(days.Value - 1);
using var connection = GetSeqConnection();
var filters = new List<string>
{
"Program = 'Dpz.Core.Web'",
"SourceContext = 'Serilog.AspNetCore.RequestLoggingMiddleware'",
"RequestPath <> '/chathub'",
"RequestPath <> '/notification'",
"RequestPath <> '/notification/negotiate'",
"RequestPath <> '/chathub/negotiate'",
"RequestPath <> '/chat/init'"
};
var filter = string.Join(" and ", filters);
try
{
var query =
$"""
select count(@Id) from stream
where {filter}
group by time(1d)
""";
var part = await connection.Data.QueryAsync(query, startDate, DateTime.Now.AddHours(8));
var list = part.Slices.Select(x => new AccessSummary
{
Date = Convert.ToDateTime(x.Time).ToString("yyyy/MM/dd"),
Count = Convert.ToInt32(x.Rows.FirstOrDefault()?.FirstOrDefault() ?? 0)
}).ToList();
return list;
}
catch (Exception e)
{
logger.LogError(e, "get latest access number fail");
return new List<AccessSummary>();
}
}
}