-
-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathServerFormatter.cs
83 lines (77 loc) · 2.91 KB
/
ServerFormatter.cs
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
using System.Net;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NReco.Logging.File;
namespace CSharpier.Cli.Server;
internal static class ServerFormatter
{
public static async Task<int> StartServer(
int? port,
ConsoleLogger logger,
string? actualConfigPath
)
{
var builder = WebApplication.CreateBuilder();
builder.WebHost.ConfigureKestrel(
(_, serverOptions) =>
{
serverOptions.Listen(IPAddress.Loopback, port ?? 0);
}
);
builder.Logging.ClearProviders();
var values = new Dictionary<string, string?>
{
["Logging:File:MaxRollingFiles"] = "1",
["Logging:File:FileSizeLimitBytes"] = "10000",
};
builder.Configuration.AddInMemoryCollection(values);
var currentPort = port ?? 0;
builder.Services.AddLogging(loggingBuilder =>
{
loggingBuilder.AddFile(
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "server{0}.log"),
o =>
{
// name files based on the port so that multiple processes can log without fighting over a file
// however before the server is started fully we won't have a port
// this empty error handler will make sure if two processes both try to use that initial file
// at the same time they won't crash
o.HandleFileError = _ => { };
o.FormatLogFileName = name =>
string.Format(name, currentPort == 0 ? string.Empty : currentPort);
}
);
});
var app = builder.Build();
app.Lifetime.ApplicationStarted.Register(() =>
{
foreach (
var address in (app as IApplicationBuilder)
.ServerFeatures.Get<IServerAddressesFeature>()
?.Addresses ?? []
)
{
var uri = new Uri(address);
currentPort = uri.Port;
logger.LogInformation("Started on " + uri.Port);
}
});
var service = new CSharpierServiceImplementation(
actualConfigPath,
// we want any further logging to happen in the file log, not out to the console
app.Services.GetRequiredService<ILogger<CSharpierServiceImplementation>>()
);
app.MapPost(
"/format",
(FormatFileParameter formatFileDto, CancellationToken cancellationToken) =>
service.FormatFile(formatFileDto, cancellationToken)
);
await app.RunAsync();
Console.ReadKey();
return 0;
}
}