From 1e5e466789d388d842874f00da16bc132b34d295 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 15 Jan 2021 08:19:29 -0600 Subject: remove Newtonsoft reference --- src/slskd/DTO/TokenResponse.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') 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 { -- cgit v1.2.3 From a37f7557010f63d725f9c82350d2b6467a189bdc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 15 Jan 2021 08:19:48 -0600 Subject: add Serilog packages, bump other versions --- src/slskd/slskd.csproj | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 779237bf..87dc2369 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -23,9 +23,13 @@ - - - + + + + + + + -- cgit v1.2.3 From 11f9439a7f701b28ac98dcb4de97b8848da8f09d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 15 Jan 2021 08:20:05 -0600 Subject: configure Serilog --- src/slskd/Program.cs | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 814cd15c..537c7f2e 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -4,6 +4,8 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; + using Serilog; + using Serilog.Events; using System; using System.Linq; using System.Reflection; @@ -24,11 +26,31 @@ } PrintBanner(version); - CreateWebHostBuilder(args).Build().Run(); + + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Debug() + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .Enrich.FromLogContext() + .WriteTo.Console() + .CreateLogger(); + + try + { + CreateWebHostBuilder(args).Build().Run(); + } + catch (Exception ex) + { + Log.Fatal(ex, "Application terminated unexpectedly"); + } + finally + { + Log.CloseAndFlush(); + } } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) + .UseSerilog() .ConfigureAppConfiguration((hostingContext, config) => { config.AddEnvironmentVariables(prefix: "SLSK_"); -- cgit v1.2.3 From 1eb59fdad8a16bca350564398ff0ae26025790c6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 15 Jan 2021 08:20:32 -0600 Subject: use serilog for diagnostics --- src/slskd/Startup.cs | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 4308add7..59dead6a 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -26,6 +26,7 @@ using slskd.Entities; using slskd.Security; using slskd.Trackers; + using Microsoft.Extensions.Logging; public class Startup { @@ -171,7 +172,8 @@ public void Configure( IApplicationBuilder app, - IWebHostEnvironment env, + IWebHostEnvironment env, + ILoggerFactory loggerFactory, IApiVersionDescriptionProvider provider, ITransferTracker tracker, IBrowseTracker browseTracker, @@ -246,6 +248,8 @@ // begin SoulseekClient implementation // --------------------------------------------------------------------------------------------------------------------------------------------- + var logger = loggerFactory.CreateLogger(); + var connectionOptions = new ConnectionOptions( readBufferSize: ReadBufferSize, writeBufferSize: WriteBufferSize, @@ -277,13 +281,22 @@ // isn't bound the minimumDiagnosticLevel should be set to None. Client.DiagnosticGenerated += (e, args) => { - lock (ConsoleSyncRoot) + static LogLevel 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 => LogLevel.Debug, + DiagnosticLevel.Info => LogLevel.Information, + DiagnosticLevel.Warning => LogLevel.Warning, + DiagnosticLevel.None => LogLevel.None, + _ => LogLevel.None + }; + + if (args.Level == DiagnosticLevel.Debug) + { + logger.Log(TranslateLogLevel(args.Level), "[DIAG] {@Message} (source: {@source})", args.Message, e.GetType().Name); + } + else + { + logger.Log(TranslateLogLevel(args.Level), "[DIAG] {@Message}", args.Message); } }; -- cgit v1.2.3 From 092626f188af4c062ed1b09363359850b774ef3b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 Jan 2021 16:12:20 -0600 Subject: configure logging --- src/slskd/Program.cs | 100 ++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 84 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 537c7f2e..6719709c 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -3,17 +3,24 @@ 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; public class Program { + public static bool Debug { get; private set; } + public static bool EnableLoki { get; private set; } + public static string LokiUrl { get; private set; } + public static void Main(string[] args) { + var runId = Guid.NewGuid(); + var assembly = Assembly.GetExecutingAssembly(); var assemblyVersion = assembly.GetName().Version; var informationVersion = assembly.GetCustomAttribute().InformationalVersion; @@ -25,14 +32,73 @@ return; } + if (args.Any(a => a == "--help" || a == "-h")) + { + PrintHelp(); + return; + } + + Debug = Debugger.IsAttached + || args.Any(a => a == "--debug" || a == "-d") + || Environment.GetEnvironmentVariable("SLSKD_DEBUG") != null; + + LokiUrl = Environment.GetEnvironmentVariable("SLSKD_LOKI_URL"); + EnableLoki = !string.IsNullOrWhiteSpace(LokiUrl) && Environment.GetEnvironmentVariable("SLSKD_ENABLE_LOKI") != null; + + if (Debug) + { + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Debug() + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .Enrich.WithProperty("RunId", runId) + .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 => EnableLoki, + config => config.GrafanaLoki( + LokiUrl, + 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("RunId", runId) + .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 => EnableLoki, + config => config.GrafanaLoki( + LokiUrl, + outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) + .CreateLogger(); + } + PrintBanner(version); - Log.Logger = new LoggerConfiguration() - .MinimumLevel.Debug() - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) - .Enrich.FromLogContext() - .WriteTo.Console() - .CreateLogger(); + var logger = Log.ForContext(); + + logger.Information("Run ID: {RunId}", runId); + + if (EnableLoki) + { + logger.Information("Logging to Loki instance at {LokiUrl}", LokiUrl); + } try { @@ -40,7 +106,7 @@ } catch (Exception ex) { - Log.Fatal(ex, "Application terminated unexpectedly"); + logger.Fatal(ex, "Application terminated unexpectedly"); } finally { @@ -50,19 +116,12 @@ public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) - .UseSerilog() .ConfigureAppConfiguration((hostingContext, config) => { config.AddEnvironmentVariables(prefix: "SLSK_"); config.AddJsonFile("config.json", optional: true, reloadOnChange: false); }) - .ConfigureLogging((context, logging) => - { - if (!System.Diagnostics.Debugger.IsAttached) - { - logging.ClearProviders(); - } - }) + .UseSerilog() .UseStartup(); public static void PrintBanner(string version) @@ -85,5 +144,14 @@ Console.WriteLine(banner); } + + public static void PrintHelp() + { + Console.WriteLine(@" +usage: slskd [options] + --version|-v displays the current version + --debug|-d runs the daemon in debug mode + --help|-h prints this help"); + } } } -- cgit v1.2.3 From 0b7131813818ab5f19904bb1ad0eefc6a2a5fe15 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 Jan 2021 16:12:35 -0600 Subject: add additional serilog sinks --- src/slskd/slskd.csproj | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 87dc2369..86faae5d 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -28,8 +28,11 @@ + + + -- cgit v1.2.3 From d33875ab9061217a6cb148e9f92553516fd3caab Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 Jan 2021 16:13:08 -0600 Subject: log diagnostics with serilog --- src/slskd/Startup.cs | 29 ++++++++++++++++------------- src/web/package-lock.json | 33 +++++++++++++++++++++++++++++++-- 2 files changed, 47 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 59dead6a..00475b58 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -27,6 +27,8 @@ using slskd.Security; using slskd.Trackers; using Microsoft.Extensions.Logging; + using System.Collections.Concurrent; + using Serilog; public class Startup { @@ -89,11 +91,15 @@ BasePath ??= "/"; BasePath = BasePath.StartsWith("/") ? BasePath : $"/{BasePath}"; - Console.WriteLine($"Serving static content from {WebRoot}"); - Console.WriteLine($"Using base request path {BasePath}"); + var logger = Log.ForContext(); + + logger.Information("Serving static content from {WebRoot}", WebRoot); + logger.Information("Using base request path {BasePath}", BasePath); } public IConfiguration Configuration { get; } + public ILoggerFactory LoggerFactory { get; private set; } + public ConcurrentDictionary Loggers { get; } = new ConcurrentDictionary(); public void ConfigureServices(IServiceCollection services) { @@ -180,6 +186,8 @@ IConversationTracker conversationTracker, IRoomTracker roomTracker) { + LoggerFactory = loggerFactory; + if (!env.IsDevelopment()) { app.UseHsts(); @@ -187,6 +195,9 @@ app.UseCors("AllowAll"); app.UseAuthentication(); + + app.UseSerilogRequestLogging(); + app.UseRouting(); app.UsePathBase(BasePath); @@ -248,8 +259,6 @@ // begin SoulseekClient implementation // --------------------------------------------------------------------------------------------------------------------------------------------- - var logger = loggerFactory.CreateLogger(); - var connectionOptions = new ConnectionOptions( readBufferSize: ReadBufferSize, writeBufferSize: WriteBufferSize, @@ -287,17 +296,11 @@ DiagnosticLevel.Info => LogLevel.Information, DiagnosticLevel.Warning => LogLevel.Warning, DiagnosticLevel.None => LogLevel.None, - _ => LogLevel.None + _ => default }; - if (args.Level == DiagnosticLevel.Debug) - { - logger.Log(TranslateLogLevel(args.Level), "[DIAG] {@Message} (source: {@source})", args.Message, e.GetType().Name); - } - else - { - logger.Log(TranslateLogLevel(args.Level), "[DIAG] {@Message}", args.Message); - } + var logger = Loggers.GetOrAdd(e.GetType().FullName, LoggerFactory.CreateLogger(e.GetType().FullName)); + logger.Log(TranslateLogLevel(args.Level), "{@Message}", args.Message); }; // bind transfer events. see TransferStateChangedEventArgs and TransferProgressEventArgs. 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", -- cgit v1.2.3 From 28ca6fc5d1001abd9d4dc2157a36fff040818867 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 Jan 2021 17:02:05 -0600 Subject: use Soulseek context for diagnostics --- src/slskd/Startup.cs | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 00475b58..6f5bc604 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -26,9 +26,9 @@ using slskd.Entities; using slskd.Security; using slskd.Trackers; - using Microsoft.Extensions.Logging; using System.Collections.Concurrent; using Serilog; + using Serilog.Events; public class Startup { @@ -98,8 +98,7 @@ } public IConfiguration Configuration { get; } - public ILoggerFactory LoggerFactory { get; private set; } - public ConcurrentDictionary Loggers { get; } = new ConcurrentDictionary(); + public ConcurrentDictionary Loggers { get; } = new ConcurrentDictionary(); public void ConfigureServices(IServiceCollection services) { @@ -179,15 +178,12 @@ public void Configure( IApplicationBuilder app, IWebHostEnvironment env, - ILoggerFactory loggerFactory, IApiVersionDescriptionProvider provider, ITransferTracker tracker, IBrowseTracker browseTracker, IConversationTracker conversationTracker, IRoomTracker roomTracker) { - LoggerFactory = loggerFactory; - if (!env.IsDevelopment()) { app.UseHsts(); @@ -290,17 +286,18 @@ // isn't bound the minimumDiagnosticLevel should be set to None. Client.DiagnosticGenerated += (e, args) => { - static LogLevel TranslateLogLevel(DiagnosticLevel diagnosticLevel) => diagnosticLevel switch + static LogEventLevel TranslateLogLevel(DiagnosticLevel diagnosticLevel) => diagnosticLevel switch { - DiagnosticLevel.Debug => LogLevel.Debug, - DiagnosticLevel.Info => LogLevel.Information, - DiagnosticLevel.Warning => LogLevel.Warning, - DiagnosticLevel.None => LogLevel.None, + DiagnosticLevel.Debug => LogEventLevel.Debug, + DiagnosticLevel.Info => LogEventLevel.Information, + DiagnosticLevel.Warning => LogEventLevel.Warning, + DiagnosticLevel.None => default, _ => default }; - var logger = Loggers.GetOrAdd(e.GetType().FullName, LoggerFactory.CreateLogger(e.GetType().FullName)); - logger.Log(TranslateLogLevel(args.Level), "{@Message}", args.Message); + 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. -- cgit v1.2.3 From 5be8b4db48c6812a137d62cddb5499d66b915ee6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 Jan 2021 17:17:08 -0600 Subject: add InstanceName --- src/slskd/Program.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 6719709c..6e48b86a 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -14,12 +14,14 @@ public class Program { public static bool Debug { get; private set; } + public static string InstanceName { get; private set; } public static bool EnableLoki { get; private set; } public static string LokiUrl { get; private set; } public static void Main(string[] args) { var runId = Guid.NewGuid(); + var processId = Environment.ProcessId; var assembly = Assembly.GetExecutingAssembly(); var assemblyVersion = assembly.GetName().Version; @@ -42,6 +44,8 @@ || args.Any(a => a == "--debug" || a == "-d") || Environment.GetEnvironmentVariable("SLSKD_DEBUG") != null; + InstanceName = Environment.GetEnvironmentVariable("SLSKD_INSTANCE_NAME") ?? "default"; + LokiUrl = Environment.GetEnvironmentVariable("SLSKD_LOKI_URL"); EnableLoki = !string.IsNullOrWhiteSpace(LokiUrl) && Environment.GetEnvironmentVariable("SLSKD_ENABLE_LOKI") != null; @@ -50,6 +54,7 @@ Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .Enrich.WithProperty("ProcessId", processId) .Enrich.WithProperty("RunId", runId) .Enrich.FromLogContext() .WriteTo.Console( @@ -72,6 +77,8 @@ .MinimumLevel.Information() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("slskd.Security.PassthroughAuthenticationHandler", LogEventLevel.Information) + .Enrich.WithProperty("InstanceName", InstanceName) + .Enrich.WithProperty("ProcessId", processId) .Enrich.WithProperty("RunId", runId) .Enrich.FromLogContext() .WriteTo.Console( @@ -92,7 +99,9 @@ PrintBanner(version); var logger = Log.ForContext(); - + + logger.Information("Instance Name: {InstanceName}", InstanceName); + logger.Information("Process ID: {ProcessId}", processId); logger.Information("Run ID: {RunId}", runId); if (EnableLoki) -- cgit v1.2.3 From 38edf59f32fb123d90f7b903edd3ddbbfab0d614 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 Jan 2021 17:27:50 -0600 Subject: rename logger config vars --- src/slskd/Program.cs | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 6e48b86a..44f52db9 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -15,8 +15,8 @@ { public static bool Debug { get; private set; } public static string InstanceName { get; private set; } - public static bool EnableLoki { get; private set; } - public static string LokiUrl { get; private set; } + public static bool LoggerLokiEnable { get; private set; } + public static string LoggerLokiUrl { get; private set; } public static void Main(string[] args) { @@ -46,14 +46,15 @@ InstanceName = Environment.GetEnvironmentVariable("SLSKD_INSTANCE_NAME") ?? "default"; - LokiUrl = Environment.GetEnvironmentVariable("SLSKD_LOKI_URL"); - EnableLoki = !string.IsNullOrWhiteSpace(LokiUrl) && Environment.GetEnvironmentVariable("SLSKD_ENABLE_LOKI") != null; + LoggerLokiUrl = Environment.GetEnvironmentVariable("SLSKD_LOGGER_LOKI_URL"); + LoggerLokiEnable = !string.IsNullOrWhiteSpace(LoggerLokiUrl) && Environment.GetEnvironmentVariable("SLSKD_LOGGER_LOKI_ENABLE") != null; if (Debug) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .Enrich.WithProperty("InstanceName", InstanceName) .Enrich.WithProperty("ProcessId", processId) .Enrich.WithProperty("RunId", runId) .Enrich.FromLogContext() @@ -65,9 +66,9 @@ outputTemplate: "[{SourceContext}] [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", rollingInterval: RollingInterval.Day)) .WriteTo.Conditional( - e => EnableLoki, + e => LoggerLokiEnable, config => config.GrafanaLoki( - LokiUrl, + LoggerLokiUrl ?? string.Empty, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) .CreateLogger(); } @@ -89,9 +90,9 @@ outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", rollingInterval: RollingInterval.Day)) .WriteTo.Conditional( - e => EnableLoki, + e => LoggerLokiEnable, config => config.GrafanaLoki( - LokiUrl, + LoggerLokiUrl ?? string.Empty, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) .CreateLogger(); } @@ -104,9 +105,9 @@ logger.Information("Process ID: {ProcessId}", processId); logger.Information("Run ID: {RunId}", runId); - if (EnableLoki) + if (LoggerLokiEnable) { - logger.Information("Logging to Loki instance at {LokiUrl}", LokiUrl); + logger.Information("Logging to Loki instance at {LoggerLokiUrl}", LoggerLokiUrl); } try -- cgit v1.2.3 From cc1381416d3bd71a9c77ff5b8793f33953f09ac6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 Jan 2021 17:28:09 -0600 Subject: log instead of console.write --- src/slskd/Startup.cs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 6f5bc604..61993997 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -29,6 +29,7 @@ using System.Collections.Concurrent; using Serilog; using Serilog.Events; + using Microsoft.Extensions.Logging; public class Startup { @@ -178,6 +179,7 @@ public void Configure( IApplicationBuilder app, IWebHostEnvironment env, + ILoggerFactory loggerFactory, IApiVersionDescriptionProvider provider, ITransferTracker tracker, IBrowseTracker browseTracker, @@ -255,6 +257,8 @@ // begin SoulseekClient implementation // --------------------------------------------------------------------------------------------------------------------------------------------- + var logger = loggerFactory.CreateLogger(); + var connectionOptions = new ConnectionOptions( readBufferSize: ReadBufferSize, writeBufferSize: WriteBufferSize, @@ -369,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); } }; @@ -386,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); } /// -- cgit v1.2.3 From 5216436871638536e2a0953ea9ec389f5970ac8d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 Jan 2021 16:01:32 -0600 Subject: add command line parsing --- .gitignore | 3 +- slskd.sln | 2 + src/slskd/Program.cs | 130 +++++++++++++++++++++++++++++++++---------------- src/slskd/slskd.csproj | 1 + 4 files changed, 94 insertions(+), 42 deletions(-) (limited to 'src') 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/Program.cs b/src/slskd/Program.cs index 44f52db9..bd1d1d77 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -10,53 +10,83 @@ 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; } - public static bool LoggerLokiEnable { 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) { - var runId = Guid.NewGuid(); - var processId = Environment.ProcessId; + 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().InformationalVersion; - var version = $"{assemblyVersion} ({informationVersion})"; + Version = $"{assemblyVersion} ({informationVersion})"; - if (args.Any(a => a == "--version" || a == "-v")) + if (ShowVersion) { - Console.WriteLine(version); + Console.WriteLine(Version); return; } - if (args.Any(a => a == "--help" || a == "-h")) + if (ShowHelp) { + if (!NoLogo) PrintBanner(Version); PrintHelp(); return; } Debug = Debugger.IsAttached - || args.Any(a => a == "--debug" || a == "-d") + || Debug || Environment.GetEnvironmentVariable("SLSKD_DEBUG") != null; - InstanceName = Environment.GetEnvironmentVariable("SLSKD_INSTANCE_NAME") ?? "default"; - - LoggerLokiUrl = Environment.GetEnvironmentVariable("SLSKD_LOGGER_LOKI_URL"); - LoggerLokiEnable = !string.IsNullOrWhiteSpace(LoggerLokiUrl) && Environment.GetEnvironmentVariable("SLSKD_LOGGER_LOKI_ENABLE") != 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("ProcessId", processId) - .Enrich.WithProperty("RunId", runId) + .Enrich.WithProperty("InvocationId", InvocationId) + .Enrich.WithProperty("ProcessId", ProcessId) .Enrich.FromLogContext() .WriteTo.Console( outputTemplate: "[{SourceContext}] [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") @@ -66,7 +96,7 @@ outputTemplate: "[{SourceContext}] [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", rollingInterval: RollingInterval.Day)) .WriteTo.Conditional( - e => LoggerLokiEnable, + e => LoggerLokiEnabled, config => config.GrafanaLoki( LoggerLokiUrl ?? string.Empty, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) @@ -78,9 +108,10 @@ .MinimumLevel.Information() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("slskd.Security.PassthroughAuthenticationHandler", LogEventLevel.Information) + .Enrich.WithProperty("Version", Version) .Enrich.WithProperty("InstanceName", InstanceName) - .Enrich.WithProperty("ProcessId", processId) - .Enrich.WithProperty("RunId", runId) + .Enrich.WithProperty("InvocationId", InvocationId) + .Enrich.WithProperty("ProcessId", ProcessId) .Enrich.FromLogContext() .WriteTo.Console( outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") @@ -90,22 +121,26 @@ outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", rollingInterval: RollingInterval.Day)) .WriteTo.Conditional( - e => LoggerLokiEnable, + e => LoggerLokiEnabled, config => config.GrafanaLoki( LoggerLokiUrl ?? string.Empty, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) .CreateLogger(); } - PrintBanner(version); + if (!NoLogo) + { + PrintBanner(Version); + } var logger = Log.ForContext(); + logger.Information("Version: {Version}", Version); logger.Information("Instance Name: {InstanceName}", InstanceName); - logger.Information("Process ID: {ProcessId}", processId); - logger.Information("Run ID: {RunId}", runId); + logger.Information("Invocation ID: {InvocationId}", InvocationId); + logger.Information("Process ID: {ProcessId}", ProcessId); - if (LoggerLokiEnable) + if (LoggerLokiEnabled) { logger.Information("Logging to Loki instance at {LoggerLokiUrl}", LoggerLokiUrl); } @@ -136,32 +171,45 @@ 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() { - Console.WriteLine(@" -usage: slskd [options] - --version|-v displays the current version - --debug|-d runs the daemon in debug mode - --help|-h prints this help"); + 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/slskd.csproj b/src/slskd/slskd.csproj index 86faae5d..ed256675 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -36,6 +36,7 @@ + -- cgit v1.2.3 From 342aca81fa1ba32c58bbab4dcab8235e1024adec Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 Jan 2021 17:22:18 -0600 Subject: tweak banner --- src/slskd/Program.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index bd1d1d77..c1380b1f 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -178,10 +178,10 @@ var centeredVersion = new string(' ', paddingLeft) + version + new string(' ', paddingRight); var banner = @$" - __ __ __ - .-----. | | .-----. | |--. .--| | - |__ --| | | |__ --| | < | _ | - |_____| |__| |_____| |__|__| |_____| + ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ + ▄▄▄▄▄▄▄ █ █ ▄▄▄▄▄▄▄ █ █▄▄▄ ▄▄▄█ █ + █__ --█ █ █ █__ --█ █ ◄█ █ - █ + █▄▄▄▄▄█ █▄▄█ █▄▄▄▄▄█ █▄▄█▄▄█ █▄▄▄▄▄█ ╒════════════════════════════════════════════════════════╕ │ GNU AFFERO GENERAL PUBLIC LICENSE │ │ https://slskd.org │ -- cgit v1.2.3