Skip to content

Commit

Permalink
fix: logger
Browse files Browse the repository at this point in the history
  • Loading branch information
GZTimeWalker committed Apr 3, 2022
1 parent 411dff9 commit d0ad466
Show file tree
Hide file tree
Showing 10 changed files with 60 additions and 67 deletions.
7 changes: 0 additions & 7 deletions GZCTF.Test/ContainerServiceTest.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,9 @@
using Xunit;
using CTFServer.Services;
using CTFServer.Services.Interface;
using Microsoft.Extensions.Configuration;
using System.IO;
using System.Text;
using Xunit.Abstractions;
using System.Collections.Generic;
using Docker.DotNet.Models;
using NLog;
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc.Testing;
using System.Net.Http;
using Microsoft.Extensions.DependencyInjection;
Expand All @@ -24,7 +18,6 @@ public class ContainerServiceTest

public ContainerServiceTest(ITestOutputHelper _output)
{
LogManager.GlobalThreshold = LogLevel.Off;
var app = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
{
Expand Down
4 changes: 4 additions & 0 deletions GZCTF/CTFServer.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@
<EmbeddedResource Include="Services\Assets\URLEmailTemplate.html" />
</ItemGroup>

<ItemGroup>
<Folder Include="log\" />
</ItemGroup>

<Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
<!-- Ensure Node.js is installed -->
<Exec Command="node --version" ContinueOnError="true">
Expand Down
4 changes: 2 additions & 2 deletions GZCTF/Controllers/GameController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ public async Task<IActionResult> Challenges([FromRoute] int id, CancellationToke
if (DateTimeOffset.UtcNow < game.StartTimeUTC)
return BadRequest(new RequestResponse("比赛还未开始"));

var participation = await participationRepository.GetParticipation(user.ActiveTeam, game, token);
var participation = await participationRepository.GetParticipationWithInstances(user.ActiveTeam, game, token);

if (participation is null)
return BadRequest(new RequestResponse("您尚未参赛"));
Expand All @@ -208,6 +208,6 @@ public async Task<IActionResult> Challenges([FromRoute] int id, CancellationToke
}
}).ToArray();

return Ok();
return Ok(res);
}
}
11 changes: 5 additions & 6 deletions GZCTF/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,12 @@
using CTFServer.Services.Interface;
using CTFServer.Utils;
using NJsonSchema.Generation;
using NLog;
using NLog.Web;
using NLog.Targets;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.AspNetCore.Mvc;
using NLog.Web;

var builder = WebApplication.CreateBuilder(args);

Expand Down Expand Up @@ -52,11 +51,11 @@
builder.Host.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
}).UseNLog();
logging.SetMinimumLevel(LogLevel.Trace);
}).UseNLog(new() { RemoveLoggerFactoryFilter = true });

Target.Register<SignalRTarget>("SignalR");
LogManager.Configuration.Variables["connectionString"] = builder.Configuration.GetConnectionString("DefaultConnection");
NLog.LogManager.Configuration.Variables["connectionString"] = builder.Configuration.GetConnectionString("DefaultConnection");

#endregion

Expand Down Expand Up @@ -225,5 +224,5 @@
}
finally
{
LogManager.Shutdown();
NLog.LogManager.Shutdown();
}
32 changes: 16 additions & 16 deletions GZCTF/Repositories/GameRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace CTFServer.Repositories;
public class GameRepository : RepositoryBase, IGameRepository
{
private readonly IMemoryCache cache;

public GameRepository(IMemoryCache memoryCache, AppDbContext _context) : base(_context)
{
cache = memoryCache;
Expand All @@ -22,7 +22,7 @@ public GameRepository(IMemoryCache memoryCache, AppDbContext _context) : base(_c
await context.SaveChangesAsync(token);
return game;
}

public Task<Game?> GetGameById(int id, CancellationToken token = default)
=> context.Games.FirstOrDefaultAsync(x => x.Id == id, token);

Expand Down Expand Up @@ -69,23 +69,23 @@ private Task<Data[]> FetchData(Game game, CancellationToken token = default)
context.Submissions.Where(s => s.Status == AnswerResult.Accepted),
i => new { i.ChallengeId, i.ParticipationId },
s => new { s.ChallengeId, s.ParticipationId },
(i, s) => new { Instance = i, Submissions = s}
).SelectMany(j => j.Submissions.DefaultIfEmpty(),
(i, s) => new { Instance = i, Submissions = s }
).SelectMany(j => j.Submissions.DefaultIfEmpty(),
(j, s) => new Data(j.Instance, s)
).ToArrayAsync(token);

private static IDictionary<int, Blood?[]> GenBloods(Data[] data)
=> data.GroupBy(j => j.Instance.Challenge).Select(g => new
{
g.Key,
Value = g.Select(c => c.Submission is null ? null : new Blood
{
g.Key,
Value = g.Select(c => c.Submission is null ? null : new Blood
{
Id = c.Instance.Participation.TeamId,
Avatar = c.Instance.Participation.Team.AvatarUrl,
Name = c.Instance.Participation.Team.Name,
SubmitTimeUTC = c.Submission.SubmitTimeUTC
}).OrderBy(t => t?.SubmitTimeUTC ?? DateTimeOffset.UtcNow).Take(3).ToArray(),
}).ToDictionary(a => a.Key.Id, a => a.Value);
Id = c.Instance.Participation.TeamId,
Avatar = c.Instance.Participation.Team.AvatarUrl,
Name = c.Instance.Participation.Team.Name,
SubmitTimeUTC = c.Submission.SubmitTimeUTC
}).OrderBy(t => t?.SubmitTimeUTC ?? DateTimeOffset.UtcNow).Take(3).ToArray(),
}).ToDictionary(a => a.Key.Id, a => a.Value);

private static IDictionary<string, IEnumerable<ChallengeInfo>> GenChallenges(Data[] data, IDictionary<int, Blood?[]> bloods)
=> data.GroupBy(g => g.Instance.Challenge)
Expand All @@ -101,7 +101,7 @@ private static IDictionary<string, IEnumerable<ChallengeInfo>> GenChallenges(Dat

private static IEnumerable<ScoreboardItem> GenScoreboardItems(Data[] data, IDictionary<int, Blood?[]> bloods)
=> data.GroupBy(j => j.Instance.Participation)
.Select(j => new
.Select(j => new
{
Item = new ScoreboardItem
{
Expand Down Expand Up @@ -161,13 +161,13 @@ private static IEnumerable<TimeLine> GenTimeLine(IEnumerable<ChallengeItem> item
{
var score = 0;
List<TimeLine> timeline = new();
foreach(var item in items.Where(i => i.SubmitTimeUTC is not null).OrderBy(i => i.SubmitTimeUTC))
foreach (var item in items.Where(i => i.SubmitTimeUTC is not null).OrderBy(i => i.SubmitTimeUTC))
{
score += item.Score;
timeline.Add(new()
{
Score = score,
Time = item.SubmitTimeUTC ?? DateTimeOffset.UtcNow // 此处不为 null
Time = item.SubmitTimeUTC!.Value // 此处不为 null
});
}
return timeline.ToArray();
Expand Down
4 changes: 2 additions & 2 deletions GZCTF/Repositories/Interface/IParticipationRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ public interface IParticipationRepository : IRepository
/// <returns></returns>
public Task<Participation> CreateParticipation(Team team, Game game, CancellationToken token = default);
/// <summary>
/// 获取比赛参与对象
/// 获取比赛参与对象以及其对应题目列表
/// </summary>
/// <param name="team">队伍对象</param>
/// <param name="game">比赛对象</param>
/// <param name="token"></param>
/// <returns></returns>
public Task<Participation?> GetParticipation(Team team, Game game, CancellationToken token = default);
public Task<Participation?> GetParticipationWithInstances(Team team, Game game, CancellationToken token = default);
}
2 changes: 1 addition & 1 deletion GZCTF/Repositories/ParticipationRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public async Task<Participation> CreateParticipation(Team team, Game game, Cance
return participation;
}

public Task<Participation?> GetParticipation(Team team, Game game, CancellationToken token = default)
public Task<Participation?> GetParticipationWithInstances(Team team, Game game, CancellationToken token = default)
=> context.Participations.Include(e => e.Team).Include(e => e.Game)
.Include(e => e.Instances).ThenInclude(e => e.Challenge)
.FirstOrDefaultAsync(e => e.Team == team && e.Game == game, token);
Expand Down
1 change: 1 addition & 0 deletions GZCTF/Services/DockerService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ public class DockerService : IContainerService
private readonly ILogger<DockerService> logger;
private readonly DockerOptions options;
private readonly DockerClient dockerClient;

public DockerService(IOptions<DockerOptions> options, ILogger<DockerService> logger)
{
this.options = options.Value;
Expand Down
10 changes: 4 additions & 6 deletions GZCTF/Utils/LogHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public static void Log<T>(this ILogger<T> _logger, string msg, string username,
if (remoteAddress is null)
return;

string ip = remoteAddress.IsIPv4MappedToIPv6 ? remoteAddress.MapToIPv4().ToString() : remoteAddress.MapToIPv6().ToString().Replace("::ffff:", "");
string ip = remoteAddress.ToString();

Log(_logger, msg, username, ip, status, level);
}
Expand All @@ -65,12 +65,10 @@ public static void Log<T>(this ILogger<T> _logger, string msg, string ip, TaskSt
/// </summary>
/// <param name="_logger">传入的 Nlog.Logger</param>
/// <param name="msg">Log 消息</param>
/// <param name="username">用户名</param>
/// <param name="uname">用户名</param>
/// <param name="ip">当前IP</param>
/// <param name="status">操作执行结果</param>
/// <param name="level">Log 级别</param>
public static void Log<T>(this ILogger<T> _logger, string msg, string username, string ip, TaskStatus status, LogLevel? level = null)
{
_logger.Log(level ?? LogLevel.Information, msg, new { uname = username, ip, status });
}
public static void Log<T>(this ILogger<T> _logger, string msg, string uname, string ip, TaskStatus status, LogLevel? level = null)
=> _logger.Log(level ?? LogLevel.Information, msg, new { uname, ip, status });
}
52 changes: 25 additions & 27 deletions GZCTF/nlog.config
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,13 @@
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="Info"
throwConfigExceptions="true"
internalLogFile="./log/internal-log.log">

<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore" />
</extensions>
internalLogLevel="info"
throwConfigExceptions="true"
internalLogFile="./log/internal.log">

<!-- enable asp.net core layout renderers -->


<!-- the targets to write to -->
<targets async="true">
<target xsi:type="Database" dbProvider="Npgsql.NpgsqlConnection, Npgsql"
Expand Down Expand Up @@ -49,27 +47,27 @@

<!-- rules to map from logger name to target -->
<rules>
<logger name="*" minlevel="Trace" writeTo="logconsole" />
<logger name="Microsoft.*" maxLevel="Warning" final="true" />
<logger name="Microsoft.AspNetCore.SpaServices.*" minLevel="Trace" final="true" />
<logger name="AspNetCoreRateLimit.*" maxLevel="Warning" final="true" />
<logger name="*" minlevel="Trace" writeTo="signalr">
<filters>
<when condition="contains('${exception:format=Type}', 'System.OperationCanceledException')"
<logger name="Microsoft.*" maxLevel="Warning" final="true" />
<logger name="Microsoft.AspNetCore.SpaServices.*" minLevel="Trace" final="true" />
<logger name="AspNetCoreRateLimit.*" maxLevel="Warning" final="true" />
<logger name="*" minlevel="Trace" writeTo="logconsole" />
<logger name="*" minlevel="Trace" writeTo="signalr">
<filters>
<when condition="contains('${exception:format=Type}', 'System.OperationCanceledException')"
action="Ignore" />
</filters>
</logger>
<logger name="*" minlevel="Trace" writeTo="logdatabase">
<filters>
<when condition="contains('${exception:format=Type}', 'System.OperationCanceledException')"
</filters>
</logger>
<logger name="*" minlevel="Trace" writeTo="logdatabase">
<filters>
<when condition="contains('${exception:format=Type}', 'System.OperationCanceledException')"
action="Ignore" />
</filters>
</logger>
<logger name="*" minlevel="Trace" writeTo="logfile" final="true">
<filters>
<when condition="contains('${exception:format=Type}', 'System.OperationCanceledException')"
</filters>
</logger>
<logger name="*" minlevel="Trace" writeTo="logfile" final="true">
<filters>
<when condition="contains('${exception:format=Type}', 'System.OperationCanceledException')"
action="Ignore" />
</filters>
</logger>
</filters>
</logger>
</rules>
</nlog>

0 comments on commit d0ad466

Please sign in to comment.