aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJP Dillingham <jpdillingham@gmail.com>2021-01-17 17:27:18 -0600
committerGitHub <noreply@github.com>2021-01-17 17:27:18 -0600
commit55ebd69d5894ea854afaa5961638c855a16f9214 (patch)
tree969a8b1969217420d16aeddee362056f62e99a7e
parent3cf673529cb73b91103f00bcaf9c15bd1148b138 (diff)
parent342aca81fa1ba32c58bbab4dcab8235e1024adec (diff)
downloadslskd-55ebd69d5894ea854afaa5961638c855a16f9214.tar.gz
Merge pull request #16 from slskd/logging
Add Serilog and configure basic logging
-rw-r--r--.gitignore3
-rw-r--r--slskd.sln2
-rw-r--r--src/slskd/DTO/TokenResponse.cs2
-rw-r--r--src/slskd/Program.cs202
-rw-r--r--src/slskd/Startup.cs43
-rw-r--r--src/slskd/slskd.csproj14
-rw-r--r--src/web/package-lock.json33
7 files changed, 252 insertions, 47 deletions
diff --git a/.gitignore b/.gitignore
index c2f69427..e3e14587 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,3 @@
.vs
-dist/ \ No newline at end of file
+dist/
+logs/ \ No newline at end of file
diff --git a/slskd.sln b/slskd.sln
index 43f6375c..32cbb00d 100644
--- a/slskd.sln
+++ b/slskd.sln
@@ -17,6 +17,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "slskd", "src\slskd\slskd.cs
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{CA2A6837-A966-4198-9B62-32D0110CA078}"
ProjectSection(SolutionItems) = preProject
+ .dockerignore = .dockerignore
+ .gitignore = .gitignore
Dockerfile = Dockerfile
LICENSE = LICENSE
README.md = README.md
diff --git a/src/slskd/DTO/TokenResponse.cs b/src/slskd/DTO/TokenResponse.cs
index c1766852..fb1b81ee 100644
--- a/src/slskd/DTO/TokenResponse.cs
+++ b/src/slskd/DTO/TokenResponse.cs
@@ -4,8 +4,8 @@
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
+ using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Authentication.JwtBearer;
- using Newtonsoft.Json;
public class TokenResponse
{
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index 814cd15c..c1380b1f 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -3,28 +3,160 @@
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.Logging;
+ using Serilog;
+ using Serilog.Events;
+ using Serilog.Sinks.Grafana.Loki;
using System;
+ using System.Diagnostics;
using System.Linq;
using System.Reflection;
+ using Utility.CommandLine;
public class Program
{
+ [Argument('h', "help", "print usage")]
+ public static bool ShowHelp { get; private set; }
+
+ [Argument('v', "version", "display version information")]
+ public static bool ShowVersion { get; private set; }
+
+ [Argument('d', "debug", "run in debug mode")]
+ public static bool Debug { get; private set; }
+
+ [Argument('n', "no-logo", "suppress logo on startup")]
+ public static bool NoLogo { get; private set; }
+
+ [Argument('i', "instance-name", "optional; a unique name for this instance")]
+ public static string InstanceName { get; private set; }
+
+ [Argument(default, "loki", "the url to a Grafana Loki instance to log to")]
+ public static string LoggerLokiUrl { get; private set; }
+
+ public static bool LoggerLokiEnabled { get; private set; }
+ public static string Version { get; private set; }
+ public static Guid InvocationId { get; private set; }
+ public static int ProcessId { get; private set; }
+
public static void Main(string[] args)
{
+ try
+ {
+ Arguments.Populate();
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Error parsing input: {ex.Message}");
+ }
+
+ InvocationId = Guid.NewGuid();
+ ProcessId = Environment.ProcessId;
+
var assembly = Assembly.GetExecutingAssembly();
var assemblyVersion = assembly.GetName().Version;
var informationVersion = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
- var version = $"{assemblyVersion} ({informationVersion})";
+ Version = $"{assemblyVersion} ({informationVersion})";
+
+ if (ShowVersion)
+ {
+ Console.WriteLine(Version);
+ return;
+ }
- if (args.Any(a => a == "--version" || a == "-v"))
+ if (ShowHelp)
{
- Console.WriteLine(version);
+ if (!NoLogo) PrintBanner(Version);
+ PrintHelp();
return;
}
- PrintBanner(version);
- CreateWebHostBuilder(args).Build().Run();
+ Debug = Debugger.IsAttached
+ || Debug
+ || Environment.GetEnvironmentVariable("SLSKD_DEBUG") != null;
+
+ InstanceName ??= Environment.GetEnvironmentVariable("SLSKD_INSTANCE_NAME") ?? "default";
+
+ LoggerLokiUrl ??= Environment.GetEnvironmentVariable("SLSKD_LOGGER_LOKI_URL");
+ LoggerLokiEnabled = !string.IsNullOrEmpty(LoggerLokiUrl);
+
+ if (Debug)
+ {
+ Log.Logger = new LoggerConfiguration()
+ .MinimumLevel.Debug()
+ .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
+ .Enrich.WithProperty("Version", Version)
+ .Enrich.WithProperty("InstanceName", InstanceName)
+ .Enrich.WithProperty("InvocationId", InvocationId)
+ .Enrich.WithProperty("ProcessId", ProcessId)
+ .Enrich.FromLogContext()
+ .WriteTo.Console(
+ outputTemplate: "[{SourceContext}] [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
+ .WriteTo.Async(config =>
+ config.File(
+ "logs/slskd-.log",
+ outputTemplate: "[{SourceContext}] [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
+ rollingInterval: RollingInterval.Day))
+ .WriteTo.Conditional(
+ e => LoggerLokiEnabled,
+ config => config.GrafanaLoki(
+ LoggerLokiUrl ?? string.Empty,
+ outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"))
+ .CreateLogger();
+ }
+ else
+ {
+ Log.Logger = new LoggerConfiguration()
+ .MinimumLevel.Information()
+ .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
+ .MinimumLevel.Override("slskd.Security.PassthroughAuthenticationHandler", LogEventLevel.Information)
+ .Enrich.WithProperty("Version", Version)
+ .Enrich.WithProperty("InstanceName", InstanceName)
+ .Enrich.WithProperty("InvocationId", InvocationId)
+ .Enrich.WithProperty("ProcessId", ProcessId)
+ .Enrich.FromLogContext()
+ .WriteTo.Console(
+ outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
+ .WriteTo.Async(config =>
+ config.File(
+ "logs/slskd-.log",
+ outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
+ rollingInterval: RollingInterval.Day))
+ .WriteTo.Conditional(
+ e => LoggerLokiEnabled,
+ config => config.GrafanaLoki(
+ LoggerLokiUrl ?? string.Empty,
+ outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"))
+ .CreateLogger();
+ }
+
+ if (!NoLogo)
+ {
+ PrintBanner(Version);
+ }
+
+ var logger = Log.ForContext<Program>();
+
+ logger.Information("Version: {Version}", Version);
+ logger.Information("Instance Name: {InstanceName}", InstanceName);
+ logger.Information("Invocation ID: {InvocationId}", InvocationId);
+ logger.Information("Process ID: {ProcessId}", ProcessId);
+
+ if (LoggerLokiEnabled)
+ {
+ logger.Information("Logging to Loki instance at {LoggerLokiUrl}", LoggerLokiUrl);
+ }
+
+ try
+ {
+ CreateWebHostBuilder(args).Build().Run();
+ }
+ catch (Exception ex)
+ {
+ logger.Fatal(ex, "Application terminated unexpectedly");
+ }
+ finally
+ {
+ Log.CloseAndFlush();
+ }
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
@@ -34,34 +166,50 @@
config.AddEnvironmentVariables(prefix: "SLSK_");
config.AddJsonFile("config.json", optional: true, reloadOnChange: false);
})
- .ConfigureLogging((context, logging) =>
- {
- if (!System.Diagnostics.Debugger.IsAttached)
- {
- logging.ClearProviders();
- }
- })
+ .UseSerilog()
.UseStartup<Startup>();
public static void PrintBanner(string version)
{
+ var padding = 56 - version.Length;
+ var paddingLeft = padding / 2;
+ var paddingRight = paddingLeft + (padding % 2);
+
+ var centeredVersion = new string(' ', paddingLeft) + version + new string(' ', paddingRight);
+
var banner = @$"
- oooo oooo .o8
- `888 `888 '888
- .oooo.o 888 .oooo.o 888 oooo .oooo888
- d88( '8 888 d88( '8 888 .8P' d88' `888
- `'Y88b. 888 `'Y88b. 888888. 888 888
- o. )88b 888 o. )88b 888 `88b. 888 888
- 8''888P' o888o 8''888P' o888o o888o `Y8bod88P
-╒═══════════════════════════════════════════════╕
-│ GNU AFFERO GENERAL PUBLIC LICENSE │
-│ slskd.org │
-│ │
-│ {version} │
-└───────────────────────────────────────────────┘
- ";
+ ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+ ▄▄▄▄▄▄▄ █ █ ▄▄▄▄▄▄▄ █ █▄▄▄ ▄▄▄█ █
+ █__ --█ █ █ █__ --█ █ ◄█ █ - █
+ █▄▄▄▄▄█ █▄▄█ █▄▄▄▄▄█ █▄▄█▄▄█ █▄▄▄▄▄█
+╒════════════════════════════════════════════════════════╕
+│ GNU AFFERO GENERAL PUBLIC LICENSE │
+│ https://slskd.org │
+│ │
+│{centeredVersion}│
+└────────────────────────────────────────────────────────┘";
Console.WriteLine(banner);
}
+
+ public static void PrintHelp()
+ {
+ static string GetLongName(ArgumentInfo info)
+ => info.Property.PropertyType == typeof(bool) ? info.LongName : $"{info.LongName} <{info.Property.PropertyType.Name.ToLowerInvariant()}>";
+
+ static string GetShortName(ArgumentInfo info)
+ => info.ShortName > 0 ? $"-{info.ShortName}|" : " ";
+
+ var arguments = Arguments.GetArgumentInfo(typeof(Program));
+ var longestName = arguments.Select(a => GetLongName(a)).Max(n => n.Length);
+
+ Console.WriteLine("\nusage: slskd [options]\n");
+ Console.WriteLine("options:");
+ foreach (var info in arguments)
+ {
+ var result = $" {GetShortName(info)}--{GetLongName(info).PadRight(longestName + 3)}{info.HelpText}";
+ Console.WriteLine(result);
+ }
+ }
}
}
diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs
index 4308add7..61993997 100644
--- a/src/slskd/Startup.cs
+++ b/src/slskd/Startup.cs
@@ -26,6 +26,10 @@
using slskd.Entities;
using slskd.Security;
using slskd.Trackers;
+ using System.Collections.Concurrent;
+ using Serilog;
+ using Serilog.Events;
+ using Microsoft.Extensions.Logging;
public class Startup
{
@@ -88,11 +92,14 @@
BasePath ??= "/";
BasePath = BasePath.StartsWith("/") ? BasePath : $"/{BasePath}";
- Console.WriteLine($"Serving static content from {WebRoot}");
- Console.WriteLine($"Using base request path {BasePath}");
+ var logger = Log.ForContext<Startup>();
+
+ logger.Information("Serving static content from {WebRoot}", WebRoot);
+ logger.Information("Using base request path {BasePath}", BasePath);
}
public IConfiguration Configuration { get; }
+ public ConcurrentDictionary<string, Serilog.ILogger> Loggers { get; } = new ConcurrentDictionary<string, Serilog.ILogger>();
public void ConfigureServices(IServiceCollection services)
{
@@ -171,7 +178,8 @@
public void Configure(
IApplicationBuilder app,
- IWebHostEnvironment env,
+ IWebHostEnvironment env,
+ ILoggerFactory loggerFactory,
IApiVersionDescriptionProvider provider,
ITransferTracker tracker,
IBrowseTracker browseTracker,
@@ -185,6 +193,9 @@
app.UseCors("AllowAll");
app.UseAuthentication();
+
+ app.UseSerilogRequestLogging();
+
app.UseRouting();
app.UsePathBase(BasePath);
@@ -246,6 +257,8 @@
// begin SoulseekClient implementation
// ---------------------------------------------------------------------------------------------------------------------------------------------
+ var logger = loggerFactory.CreateLogger<Startup>();
+
var connectionOptions = new ConnectionOptions(
readBufferSize: ReadBufferSize,
writeBufferSize: WriteBufferSize,
@@ -277,14 +290,18 @@
// isn't bound the minimumDiagnosticLevel should be set to None.
Client.DiagnosticGenerated += (e, args) =>
{
- lock (ConsoleSyncRoot)
+ static LogEventLevel TranslateLogLevel(DiagnosticLevel diagnosticLevel) => diagnosticLevel switch
{
- if (args.Level == DiagnosticLevel.Debug) Console.ForegroundColor = ConsoleColor.DarkGray;
- if (args.Level == DiagnosticLevel.Warning) Console.ForegroundColor = ConsoleColor.Yellow;
-
- Console.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] [DIAGNOSTIC:{e.GetType().Name}] [{args.Level}] {args.Message}");
- Console.ResetColor();
- }
+ DiagnosticLevel.Debug => LogEventLevel.Debug,
+ DiagnosticLevel.Info => LogEventLevel.Information,
+ DiagnosticLevel.Warning => LogEventLevel.Warning,
+ DiagnosticLevel.None => default,
+ _ => default
+ };
+
+ var logger = Loggers.GetOrAdd(e.GetType().FullName, Log.ForContext("SourceContext", "Soulseek").ForContext("SoulseekContext", e.GetType().FullName));
+
+ logger.Write(TranslateLogLevel(args.Level), "{@Message}", args.Message);
};
// bind transfer events. see TransferStateChangedEventArgs and TransferProgressEventArgs.
@@ -356,14 +373,14 @@
Client.Disconnected += async (e, args) =>
{
- Console.WriteLine($"Disconnected from Soulseek server: {args.Message}");
+ logger.LogWarning("Disconnected from Soulseek server: {Message}", args.Message, args.Exception);
// don't reconnect if the disconnecting Exception is either of these types.
// if KickedFromServerException, another client was most likely signed in, and retrying will cause a connect loop.
// if ObjectDisposedException, the client is shutting down.
if (!(args.Exception is KickedFromServerException || args.Exception is ObjectDisposedException))
{
- Console.WriteLine($"Attepting to reconnect...");
+ logger.LogWarning("Attepting to reconnect...");
await Client.ConnectAsync(Username, Password);
}
};
@@ -373,7 +390,7 @@
await Client.ConnectAsync(Username, Password);
}).GetAwaiter().GetResult();
- Console.WriteLine($"Connected and logged in.");
+ logger.LogInformation("Connected and logged in as {Username}", Username);
}
/// <summary>
diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj
index 779237bf..ed256675 100644
--- a/src/slskd/slskd.csproj
+++ b/src/slskd/slskd.csproj
@@ -23,12 +23,20 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.9" />
- <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="4.1.1" />
- <PackageReference Include="Microsoft.Data.Sqlite" Version="3.1.9" />
+ <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.2" />
+ <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="4.2.0" />
+ <PackageReference Include="Microsoft.Data.Sqlite" Version="5.0.2" />
+ <PackageReference Include="Serilog" Version="2.10.0" />
+ <PackageReference Include="Serilog.AspNetCore" Version="3.4.0" />
+ <PackageReference Include="Serilog.Sinks.Async" Version="1.4.0" />
+ <PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
+ <PackageReference Include="Serilog.Sinks.File" Version="4.1.0" />
+ <PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="5.0.0" />
+ <PackageReference Include="Serilog.Sinks.Http" Version="7.2.0" />
<PackageReference Include="Soulseek" Version="1.0.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.8.0" />
+ <PackageReference Include="Utility.CommandLine.Arguments" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
diff --git a/src/web/package-lock.json b/src/web/package-lock.json
index 4fb80e76..fa7e1d29 100644
--- a/src/web/package-lock.json
+++ b/src/web/package-lock.json
@@ -3432,6 +3432,15 @@
"integrity": "sha512-1Yj8h9Q+QDF5FzhMs/c9+6UntbD5MkRfRwac8DoEm9ZfUBZ7tZ55YcGVAzEe4bXsdQHEk+s9S5wsOKVdZrw0tQ==",
"optional": true
},
+ "bindings": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",
+ "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==",
+ "optional": true,
+ "requires": {
+ "file-uri-to-path": "1.0.0"
+ }
+ },
"bluebird": {
"version": "3.7.2",
"resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz",
@@ -6315,6 +6324,12 @@
}
}
},
+ "file-uri-to-path": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",
+ "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==",
+ "optional": true
+ },
"filesize": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/filesize/-/filesize-6.1.0.tgz",
@@ -10076,6 +10091,12 @@
"resolved": "https://registry.npmjs.org/multicast-dns-service-types/-/multicast-dns-service-types-1.1.0.tgz",
"integrity": "sha1-iZ8R2WhuXgXLkbNdXw5jt3PPyQE="
},
+ "nan": {
+ "version": "2.14.2",
+ "resolved": "https://registry.npmjs.org/nan/-/nan-2.14.2.tgz",
+ "integrity": "sha512-M2ufzIiINKCuDfBSAUr1vWQ+vuVcA9kqx8JJUsbQi6yf1uGRyb7HfpdfUr5qLXf3B/t8dPvcjhKMmlfnP47EzQ==",
+ "optional": true
+ },
"nanoid": {
"version": "3.1.20",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.1.20.tgz",
@@ -15247,7 +15268,11 @@
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.13.tgz",
"integrity": "sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw==",
- "optional": true
+ "optional": true,
+ "requires": {
+ "bindings": "^1.5.0",
+ "nan": "^2.12.1"
+ }
},
"glob-parent": {
"version": "3.1.0",
@@ -15855,7 +15880,11 @@
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.13.tgz",
"integrity": "sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw==",
- "optional": true
+ "optional": true,
+ "requires": {
+ "bindings": "^1.5.0",
+ "nan": "^2.12.1"
+ }
},
"glob-parent": {
"version": "3.1.0",