From 91ad4826bbd0d89f69276ea0789e1498f2a92801 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 02:19:36 -0500 Subject: stub endpoints to list and read log files --- src/slskd/Core/API/Controllers/LogsController.cs | 59 +++++++++++++++++++++++- 1 file changed, 58 insertions(+), 1 deletion(-) (limited to 'src/slskd/Core/API') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 8055c696..a12d9187 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -32,9 +32,14 @@ namespace slskd.Core.API { + using System; + using System.IO; + using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; + using Serilog; + using slskd.Files; /// /// Logs. @@ -46,15 +51,67 @@ namespace slskd.Core.API [Consumes("application/json")] public class LogsController : ControllerBase { + public LogsController( + FileService fileService, + OptionsAtStartup optionsAtStartup) + { + Files = fileService; + OptionsAtStartup = optionsAtStartup; + } + + private FileService Files { get; } + private OptionsAtStartup OptionsAtStartup { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + /// /// Gets the last few application logs. /// /// - [HttpGet] + [HttpGet("buffer")] [Authorize(Policy = AuthPolicy.Any)] public IActionResult Logs() { return Ok(Program.LogBuffer); } + + [HttpGet] + [Authorize(Policy = AuthPolicy.Any)] + public async Task List() + { + var directory = await Files.ListDirectoryContentsAsync(System.IO.Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions + { + AttributesToSkip = FileAttributes.System, + RecurseSubdirectories = false, + }); + + return Ok(directory.Files); + } + + [HttpGet("{filename}")] + [Authorize(Policy = AuthPolicy.Any)] + public async Task Get(string filename, [FromQuery] bool download = false) + { + filename = FileSafety.GetFileNameSafely(filename); + + try + { + var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, filename)); + + if (download) + { + return File(stream, "text/plain", filename); + } + + return File(stream, "text/plain"); + } + catch (UnauthorizedException) + { + return NotFound(); + } + catch (NotFoundException) + { + return NotFound(); + } + } } } -- cgit v1.2.3 From 2c719dd8f5f330de61caf850c9087b5b989c1611 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 18:10:29 -0500 Subject: docs, change routes, lock endpoints down to administrators only --- src/slskd/Core/API/Controllers/LogsController.cs | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) (limited to 'src/slskd/Core/API') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index a12d9187..465993c1 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -67,15 +67,19 @@ namespace slskd.Core.API /// Gets the last few application logs. /// /// - [HttpGet("buffer")] - [Authorize(Policy = AuthPolicy.Any)] + [HttpGet("live")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public IActionResult Logs() { return Ok(Program.LogBuffer); } - [HttpGet] - [Authorize(Policy = AuthPolicy.Any)] + /// + /// Lists the log files currently on disk. + /// + /// + [HttpGet("files")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public async Task List() { var directory = await Files.ListDirectoryContentsAsync(System.IO.Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions @@ -87,8 +91,14 @@ namespace slskd.Core.API return Ok(directory.Files); } - [HttpGet("{filename}")] - [Authorize(Policy = AuthPolicy.Any)] + /// + /// Retrieves the requested log file from disk. + /// + /// + /// + /// + [HttpGet("files/{filename}")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public async Task Get(string filename, [FromQuery] bool download = false) { filename = FileSafety.GetFileNameSafely(filename); -- cgit v1.2.3 From f76b210689cf1d0bc8b3f0d971194263eb66b3d7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 18:25:11 -0500 Subject: remove uneccessary import --- src/slskd/Core/API/Controllers/LogsController.cs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) (limited to 'src/slskd/Core/API') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 465993c1..590ee6b7 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -52,15 +52,12 @@ namespace slskd.Core.API public class LogsController : ControllerBase { public LogsController( - FileService fileService, - OptionsAtStartup optionsAtStartup) + FileService fileService) { Files = fileService; - OptionsAtStartup = optionsAtStartup; } private FileService Files { get; } - private OptionsAtStartup OptionsAtStartup { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); /// -- cgit v1.2.3 From bb25e7accb1e47bfea4ddbb998106ad7365a88a6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 19:08:47 -0500 Subject: add log file fetch and download --- src/slskd/Core/API/Controllers/LogsController.cs | 92 ++++++++++++++++++++++-- 1 file changed, 88 insertions(+), 4 deletions(-) (limited to 'src/slskd/Core/API') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 590ee6b7..43300e63 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -98,27 +98,111 @@ namespace slskd.Core.API [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public async Task Get(string filename, [FromQuery] bool download = false) { - filename = FileSafety.GetFileNameSafely(filename); + if (string.IsNullOrWhiteSpace(filename)) + { + return BadRequest("Filename is required"); + } + + if (filename.ContainsAny('/', '\\')) + { + return BadRequest("Filename must not contain a path"); + } + + var sanitizedFilename = FileSafety.GetFileNameSafely(filename, sanitize: true); + + if (!sanitizedFilename.Equals(filename, StringComparison.OrdinalIgnoreCase)) + { + Log.Warning("Input filename {Filename} sanitized to {Sanitized}", filename, sanitizedFilename); + return BadRequest("Filename contains one or more invalid characters"); + } try { - var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, filename)); + var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, sanitizedFilename)); if (download) { return File(stream, "text/plain", filename); } - return File(stream, "text/plain"); + var logs = await ParseLogEntriesAsync(stream); + + return Ok(logs); } catch (UnauthorizedException) { - return NotFound(); + return Unauthorized(); } catch (NotFoundException) { return NotFound(); } } + + private async Task> ParseLogEntriesAsync(Stream stream) + { + Dictionary levels = new() + { + ["VRB"] = nameof(Serilog.Events.LogEventLevel.Verbose), + ["DBG"] = nameof(Serilog.Events.LogEventLevel.Debug), + ["INF"] = nameof(Serilog.Events.LogEventLevel.Information), + ["WRN"] = nameof(Serilog.Events.LogEventLevel.Warning), + ["ERR"] = nameof(Serilog.Events.LogEventLevel.Error), + ["FTL"] = nameof(Serilog.Events.LogEventLevel.Fatal), + }; + + var list = new List(); + + var reader = new StreamReader(stream); + string line; + + while ((line = await reader.ReadLineAsync()) is not null) + { + if (line.Length == 0) + { + continue; + } + + try + { + // if the line isn't a log, append it to the previous message + if (!line.StartsWith('[')) + { + var lastIndex = list.Count - 1; + + if (lastIndex >= 0) + { + var old = list[lastIndex]; + + list[lastIndex] = new LogRecord + { + Timestamp = old.Timestamp, + Level = old.Level, + Message = old.Message + '\n' + line, + }; + } + + continue; + } + + var parts = line.TrimStart('[').Split(']', count: 2); + var meta = parts[0].Split(' '); + + list.Add(new LogRecord + { + Timestamp = DateTime.Parse(meta[0]), + Level = levels[meta[1]], + Message = parts[1].TrimStart(), + }); + } + catch (Exception ex) + { + Log.Warning(ex, "Error parsing log message: {Message}", ex.Message); + continue; + } + } + + return list; + } } } -- cgit v1.2.3 From 3b2d0c62f410a4db800055b831bf37c1e512c1b7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 19:10:36 -0500 Subject: wip of log zip --- src/slskd/Core/API/Controllers/LogsController.cs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'src/slskd/Core/API') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 43300e63..569848b2 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -33,7 +33,10 @@ namespace slskd.Core.API { using System; + using System.Collections.Generic; using System.IO; + using System.IO.Compression; + using System.Threading; using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; @@ -77,7 +80,7 @@ namespace slskd.Core.API /// [HttpGet("files")] [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] - public async Task List() + public async Task List(CancellationToken cancellationToken, [FromQuery] bool download = false) { var directory = await Files.ListDirectoryContentsAsync(System.IO.Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions { @@ -85,6 +88,16 @@ namespace slskd.Core.API RecurseSubdirectories = false, }); + if (download) + { + var stream = new MemoryStream(); + await ZipFile.CreateFromDirectoryAsync(Program.LogDirectory, stream, cancellationToken: cancellationToken); + + var now = DateTime.UtcNow; + + return File(stream, "application/zip", $"logs-{now:yyyyMMdd}-{new DateTimeOffset(now).ToUnixTimeMilliseconds}.zip"); + } + return Ok(directory.Files); } -- cgit v1.2.3 From e5a8ae30b640212386cbb4e1fffd2ae937234793 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Aug 2026 08:55:24 -0500 Subject: forget about downloading a zip --- src/slskd/Core/API/Controllers/LogsController.cs | 11 ----------- 1 file changed, 11 deletions(-) (limited to 'src/slskd/Core/API') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 569848b2..a35c6097 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -35,7 +35,6 @@ namespace slskd.Core.API using System; using System.Collections.Generic; using System.IO; - using System.IO.Compression; using System.Threading; using System.Threading.Tasks; using Asp.Versioning; @@ -88,16 +87,6 @@ namespace slskd.Core.API RecurseSubdirectories = false, }); - if (download) - { - var stream = new MemoryStream(); - await ZipFile.CreateFromDirectoryAsync(Program.LogDirectory, stream, cancellationToken: cancellationToken); - - var now = DateTime.UtcNow; - - return File(stream, "application/zip", $"logs-{now:yyyyMMdd}-{new DateTimeOffset(now).ToUnixTimeMilliseconds}.zip"); - } - return Ok(directory.Files); } -- cgit v1.2.3 From ec02691a206451e9e9c11a2f305ab928c6f9676b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:11:38 -0500 Subject: add regex for parsing log lines --- src/slskd/Core/API/Controllers/LogsController.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src/slskd/Core/API') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index a35c6097..fff5e843 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -35,6 +35,7 @@ namespace slskd.Core.API using System; using System.Collections.Generic; using System.IO; + using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Asp.Versioning; @@ -61,6 +62,7 @@ namespace slskd.Core.API private FileService Files { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); + private Regex LogLineParseRegex { get; } = new Regex(@"^(\[?([a-zA-Z\.]*)\]?\s)?(\[((\d{4}-\d{2}-\d{2})T)?(\d{2}:\d{2}:\d{2}(?:.\d{3})?)\s([A-Z]+)\]\s)?(.*)", RegexOptions.Compiled); /// /// Gets the last few application logs. -- cgit v1.2.3 From 5b063c478b5d5f8e694a5cdea76af0d8eada3150 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:11:53 -0500 Subject: leave note about streaming optimization --- src/slskd/Core/API/Controllers/LogsController.cs | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src/slskd/Core/API') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index fff5e843..13f8ab95 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -129,6 +129,10 @@ namespace slskd.Core.API return File(stream, "text/plain", filename); } + // future optimization: use IAsyncEnumerable to 'stream' the log records instead of beating up + // memory to build a list. save each log in memory and then emit it when the next log + // (starting with '[') is read, which indicates that it's not multi-line. in other words, a 1-log buffer + // that is flushed when the next log is read, or the file is complete var logs = await ParseLogEntriesAsync(stream); return Ok(logs); -- cgit v1.2.3 From ea4ca200cd6dda759917dcd76d47d2bddfa5d2f5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:12:23 -0500 Subject: break if the file is being appended to avoid an endless loop --- src/slskd/Core/API/Controllers/LogsController.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'src/slskd/Core/API') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 13f8ab95..d7e011eb 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -161,6 +161,8 @@ namespace slskd.Core.API var list = new List(); + var currentLength = stream.Length; + var reader = new StreamReader(stream); string line; @@ -171,6 +173,15 @@ namespace slskd.Core.API continue; } + if (stream.Position > currentLength) + { + // if we're reading the latest file, Serilog can append it while we're inside of this loop, + // or worse, a problem inside this loop appends lines. if this happens the position will grow + // beyond the length at the start + Log.Information("Parsing of log file {Filename} stopped before end of file; log was appended during the read"); + break; + } + try { // if the line isn't a log, append it to the previous message -- cgit v1.2.3 From e2bc14a1572c4a3d035ac7a4ffe47cff35fd2e16 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:12:39 -0500 Subject: parse logs with the regex --- src/slskd/Core/API/Controllers/LogsController.cs | 48 +++++++++++++++++++++--- 1 file changed, 43 insertions(+), 5 deletions(-) (limited to 'src/slskd/Core/API') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index d7e011eb..1c1f057b 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -204,14 +204,52 @@ namespace slskd.Core.API continue; } - var parts = line.TrimStart('[').Split(']', count: 2); - var meta = parts[0].Split(' '); + /* + there should be 3 possible line types: + + debug: + [Some.Context] [2000-1-1T11:11:11 WRN] foo bar + + info: + [2000-1-1T11:11:11 WRN] foo bar + + line wrap/newline: + foo bar + + additionally, date was added to disk log files around 9/1/26, so we need to gracefully handle + cases where the timestamp contains only hh:mm:ss, and substitute the unix epoch for the date + + the regex includes 8 matching groups (hopefully this comment and the regex don't diverge!) + using the debug log as an example, the groups are: + + 0. [Some.Context] [2026-08-29T11:11:11 WRN] foo bar + 1. [Some.Context] + 2. Some.Context + 3. [2000-01-01T11:11:11 WRN] + 4. 2000-01-01T + 5. 2000-01-01 + 6. 11:11:11 + 7. WRN + 8. foo bar + + the final group in the regex is simply `.*`, so we're guaranteed to get a match for every line + */ + match = LogLineParseRegex.Match(line); + + var grp = match.Groups; + + var date = grp[5].Success ? DateOnly.Parse(grp[5].Value) : DateOnly.FromDateTime(DateTime.UnixEpoch); + var time = grp[6].Success ? TimeOnly.Parse(grp[6].Value) : TimeOnly.FromDateTime(DateTime.UnixEpoch); + var dateTime = date.ToDateTime(time); + + var level = levels.ContainsKey(grp[7].Value) ? levels[grp[7].Value] : null; list.Add(new LogRecord { - Timestamp = DateTime.Parse(meta[0]), - Level = levels[meta[1]], - Message = parts[1].TrimStart(), + Context = grp[2].Value, + Timestamp = dateTime, + Level = level, + Message = grp[8].Value, }); } catch (Exception ex) -- cgit v1.2.3 From 0ef9cd71e115642cce876372c76fd3a1d8de6a4b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:13:02 -0500 Subject: wip --- src/slskd/Core/API/Controllers/LogsController.cs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) (limited to 'src/slskd/Core/API') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 1c1f057b..1a3e027f 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -165,6 +165,7 @@ namespace slskd.Core.API var reader = new StreamReader(stream); string line; + Match match = default; while ((line = await reader.ReadLineAsync()) is not null) { @@ -251,14 +252,31 @@ namespace slskd.Core.API Level = level, Message = grp[8].Value, }); + + Log.Information("Added: {Text}", grp[8].Value); } catch (Exception ex) { - Log.Warning(ex, "Error parsing log message: {Message}", ex.Message); - continue; + Log.Debug("Error parsing log message: {Message}. Line: {Line}", ex.Message, line); + + Log.Warning("Got {GroupCount} groups", match.Groups.Count); + + foreach (var key in match.Groups.Keys) + { + Log.Warning("Key: {Key}, Success: {Success}, Value: {Value}", key, match.Groups[key].Success, match.Groups[key].Value); + } + + break; + + list.Add(new LogRecord + { + Message = line, + }); } } + Log.Information("Returned {Lines}", list.Count); + return list; } } -- cgit v1.2.3 From 58a289bcdcf4d649d94ee6058c40ee7197d95209 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 25 Sep 2026 09:29:34 -0500 Subject: strip out complicated parsing --- src/slskd/Core/API/Controllers/LogsController.cs | 176 +++-------------------- 1 file changed, 21 insertions(+), 155 deletions(-) (limited to 'src/slskd/Core/API') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 1a3e027f..6ef4a7b6 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -33,10 +33,8 @@ namespace slskd.Core.API { using System; - using System.Collections.Generic; using System.IO; - using System.Text.RegularExpressions; - using System.Threading; + using System.Linq; using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; @@ -54,15 +52,13 @@ namespace slskd.Core.API [Consumes("application/json")] public class LogsController : ControllerBase { - public LogsController( - FileService fileService) + public LogsController(FileService fileService) { Files = fileService; } private FileService Files { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); - private Regex LogLineParseRegex { get; } = new Regex(@"^(\[?([a-zA-Z\.]*)\]?\s)?(\[((\d{4}-\d{2}-\d{2})T)?(\d{2}:\d{2}:\d{2}(?:.\d{3})?)\s([A-Z]+)\]\s)?(.*)", RegexOptions.Compiled); /// /// Gets the last few application logs. @@ -81,26 +77,29 @@ namespace slskd.Core.API /// [HttpGet("files")] [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] - public async Task List(CancellationToken cancellationToken, [FromQuery] bool download = false) + public async Task List() { - var directory = await Files.ListDirectoryContentsAsync(System.IO.Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions + var directory = await Files.ListDirectoryContentsAsync(Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions { - AttributesToSkip = FileAttributes.System, + IgnoreInaccessible = true, + AttributesToSkip = FileAttributes.System | FileAttributes.Hidden | FileAttributes.ReparsePoint, RecurseSubdirectories = false, }); - return Ok(directory.Files); + var logs = directory.Files.Where(f => f.Name.EndsWith(".log", StringComparison.OrdinalIgnoreCase)); + + return Ok(logs); } /// - /// Retrieves the requested log file from disk. + /// Retrieves the requested log file from disk as plain text. /// - /// - /// + /// The name of the log file. + /// A value indicating whether the file should be sent as an attachment. /// [HttpGet("files/{filename}")] [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] - public async Task Get(string filename, [FromQuery] bool download = false) + public IActionResult Get(string filename, [FromQuery] bool download = false) { if (string.IsNullOrWhiteSpace(filename)) { @@ -120,22 +119,22 @@ namespace slskd.Core.API return BadRequest("Filename contains one or more invalid characters"); } + if (!sanitizedFilename.EndsWith(".log", StringComparison.OrdinalIgnoreCase)) + { + return BadRequest("Only .log files may be retrieved"); + } + try { var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, sanitizedFilename)); + const string contentType = "text/plain; charset=utf-8"; if (download) { - return File(stream, "text/plain", filename); + return File(stream, contentType, filename); } - // future optimization: use IAsyncEnumerable to 'stream' the log records instead of beating up - // memory to build a list. save each log in memory and then emit it when the next log - // (starting with '[') is read, which indicates that it's not multi-line. in other words, a 1-log buffer - // that is flushed when the next log is read, or the file is complete - var logs = await ParseLogEntriesAsync(stream); - - return Ok(logs); + return File(stream, contentType); } catch (UnauthorizedException) { @@ -146,138 +145,5 @@ namespace slskd.Core.API return NotFound(); } } - - private async Task> ParseLogEntriesAsync(Stream stream) - { - Dictionary levels = new() - { - ["VRB"] = nameof(Serilog.Events.LogEventLevel.Verbose), - ["DBG"] = nameof(Serilog.Events.LogEventLevel.Debug), - ["INF"] = nameof(Serilog.Events.LogEventLevel.Information), - ["WRN"] = nameof(Serilog.Events.LogEventLevel.Warning), - ["ERR"] = nameof(Serilog.Events.LogEventLevel.Error), - ["FTL"] = nameof(Serilog.Events.LogEventLevel.Fatal), - }; - - var list = new List(); - - var currentLength = stream.Length; - - var reader = new StreamReader(stream); - string line; - Match match = default; - - while ((line = await reader.ReadLineAsync()) is not null) - { - if (line.Length == 0) - { - continue; - } - - if (stream.Position > currentLength) - { - // if we're reading the latest file, Serilog can append it while we're inside of this loop, - // or worse, a problem inside this loop appends lines. if this happens the position will grow - // beyond the length at the start - Log.Information("Parsing of log file {Filename} stopped before end of file; log was appended during the read"); - break; - } - - try - { - // if the line isn't a log, append it to the previous message - if (!line.StartsWith('[')) - { - var lastIndex = list.Count - 1; - - if (lastIndex >= 0) - { - var old = list[lastIndex]; - - list[lastIndex] = new LogRecord - { - Timestamp = old.Timestamp, - Level = old.Level, - Message = old.Message + '\n' + line, - }; - } - - continue; - } - - /* - there should be 3 possible line types: - - debug: - [Some.Context] [2000-1-1T11:11:11 WRN] foo bar - - info: - [2000-1-1T11:11:11 WRN] foo bar - - line wrap/newline: - foo bar - - additionally, date was added to disk log files around 9/1/26, so we need to gracefully handle - cases where the timestamp contains only hh:mm:ss, and substitute the unix epoch for the date - - the regex includes 8 matching groups (hopefully this comment and the regex don't diverge!) - using the debug log as an example, the groups are: - - 0. [Some.Context] [2026-08-29T11:11:11 WRN] foo bar - 1. [Some.Context] - 2. Some.Context - 3. [2000-01-01T11:11:11 WRN] - 4. 2000-01-01T - 5. 2000-01-01 - 6. 11:11:11 - 7. WRN - 8. foo bar - - the final group in the regex is simply `.*`, so we're guaranteed to get a match for every line - */ - match = LogLineParseRegex.Match(line); - - var grp = match.Groups; - - var date = grp[5].Success ? DateOnly.Parse(grp[5].Value) : DateOnly.FromDateTime(DateTime.UnixEpoch); - var time = grp[6].Success ? TimeOnly.Parse(grp[6].Value) : TimeOnly.FromDateTime(DateTime.UnixEpoch); - var dateTime = date.ToDateTime(time); - - var level = levels.ContainsKey(grp[7].Value) ? levels[grp[7].Value] : null; - - list.Add(new LogRecord - { - Context = grp[2].Value, - Timestamp = dateTime, - Level = level, - Message = grp[8].Value, - }); - - Log.Information("Added: {Text}", grp[8].Value); - } - catch (Exception ex) - { - Log.Debug("Error parsing log message: {Message}. Line: {Line}", ex.Message, line); - - Log.Warning("Got {GroupCount} groups", match.Groups.Count); - - foreach (var key in match.Groups.Keys) - { - Log.Warning("Key: {Key}, Success: {Success}, Value: {Value}", key, match.Groups[key].Success, match.Groups[key].Value); - } - - break; - - list.Add(new LogRecord - { - Message = line, - }); - } - } - - Log.Information("Returned {Lines}", list.Count); - - return list; - } } } -- cgit v1.2.3 From f32f73b402e9bfd5aca47cb94a245fccbd21482f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Oct 2026 18:40:32 -0500 Subject: tweak controller --- src/slskd/Core/API/Controllers/LogsController.cs | 33 ++++++++++++------------ 1 file changed, 17 insertions(+), 16 deletions(-) (limited to 'src/slskd/Core/API') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 6ef4a7b6..a83e608c 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -38,6 +38,7 @@ namespace slskd.Core.API using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Serilog; using slskd.Files; @@ -58,7 +59,7 @@ namespace slskd.Core.API } private FileService Files { get; } - private ILogger Log { get; } = Serilog.Log.ForContext(); + private ILogger Log { get; } = Serilog.Log.ForContext(); /// /// Gets the last few application logs. @@ -79,6 +80,11 @@ namespace slskd.Core.API [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public async Task List() { + if (!Directory.Exists(Path.GetFullPath(Program.LogDirectory))) + { + return NotFound(); + } + var directory = await Files.ListDirectoryContentsAsync(Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions { IgnoreInaccessible = true, @@ -95,11 +101,12 @@ namespace slskd.Core.API /// Retrieves the requested log file from disk as plain text. /// /// The name of the log file. - /// A value indicating whether the file should be sent as an attachment. /// [HttpGet("files/{filename}")] + [Produces("text/plain")] + [ProducesResponseType(typeof(string), StatusCodes.Status200OK, contentType: "text/plain")] [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] - public IActionResult Get(string filename, [FromQuery] bool download = false) + public IActionResult Get([FromRoute] string filename) { if (string.IsNullOrWhiteSpace(filename)) { @@ -121,29 +128,23 @@ namespace slskd.Core.API if (!sanitizedFilename.EndsWith(".log", StringComparison.OrdinalIgnoreCase)) { - return BadRequest("Only .log files may be retrieved"); + return StatusCode(StatusCodes.Status403Forbidden, "Only .log files may be retrieved"); } try { var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, sanitizedFilename)); - const string contentType = "text/plain; charset=utf-8"; - - if (download) - { - return File(stream, contentType, filename); - } - - return File(stream, contentType); - } - catch (UnauthorizedException) - { - return Unauthorized(); + return File(stream, "text/plain; charset=utf-8", enableRangeProcessing: true); } catch (NotFoundException) { return NotFound(); } + catch (Exception ex) + { + Log.Error(ex, "Failed to retrieve log file {Filename}: {Message}", filename, ex.Message); + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } } } } -- cgit v1.2.3