Files
Anubis/src/Anubis.Server/JsonLog.cs
T
Alby96andClaude Opus 5.5 6e365673b8
ci / test (postgres) (push) Successful in 6m25s
ci / test (sqlite) (push) Successful in 4m1s
ci / test (postgres) (pull_request) Failing after 6m4s
ci / image (push) Canceled after 0s
ci / test (sqlite) (pull_request) Successful in 4m34s
ci / image (pull_request) Skipped
Collect diagnostics for the analysis of a long run and package a Windows trial release (refs #95 #55)
The 48-hour soak run at home kept being cut short by the host, never by Anubis.
The user will instead run a release for as long as they like and paste back a
report, so the bot now records what that report needs (ADR 0013).

- Every 5 minutes and at each start, a process sample goes to diagnostic_samples:
  memory, GC, threads, handles, CPU, exceptions, database size, log warnings and
  errors, and outbound HTTP calls by destination with duration buckets, read from
  the System.Net.Http meter without any new package.
- Every scheduled job run goes to job_runs. Both tables keep 30 days.
- The Markdown report (at most 60 KB, redacted, user folders masked) adds
  findings, the soak checks, starts and silences, jobs, calls, grouped log
  warnings and errors, and resources over time with their slopes. It comes from
  "anubis diagnostics", GET /api/diagnostica.md and a button in Diario e sistema.
- New {long} column token: SQLite STRICT tables reject BIGINT.
- "tasks release-win" builds the trial zip with a start script, a script that
  writes the report, and Italian instructions. Version 0.7.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:57:03 +01:00

141 lines
4.4 KiB
C#

using System.Collections.Concurrent;
using System.Globalization;
using System.Text;
using System.Text.Json;
using Anubis.Core;
using Anubis.Diagnostics;
namespace Anubis.Server;
/// <summary>
/// Structured logs (SPEC 2.2, issue #10): one JSON object per line on the console and in a daily file under
/// data/logs, every text passed through the <see cref="Redactor"/> so no secret reaches a log. The last 14 files are kept.
/// </summary>
internal sealed class JsonLogProvider : ILoggerProvider
{
public const int KeepFiles = 14;
private readonly string? _folder;
private readonly IClock _clock;
private readonly bool _console;
private readonly Lock _gate = new();
private readonly ConcurrentDictionary<string, JsonLogger> _loggers = new(StringComparer.Ordinal);
private StreamWriter? _file;
private string? _fileDay;
public JsonLogProvider(string? folder, IClock clock, bool console)
{
_folder = folder;
_clock = clock;
_console = console;
}
public ILogger CreateLogger(string categoryName) => _loggers.GetOrAdd(categoryName, name => new JsonLogger(name, this));
internal void Write(string category, LogLevel level, EventId eventId, string message, Exception? exception)
{
LogCounter.Record(level);
var now = _clock.UtcNow;
using var buffer = new MemoryStream();
using (var json = new Utf8JsonWriter(buffer))
{
json.WriteStartObject();
json.WriteString("at", now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture));
json.WriteString("level", level.ToString().ToLowerInvariant());
json.WriteString("category", category);
if (eventId.Id != 0)
{
json.WriteNumber("event", eventId.Id);
}
json.WriteString("message", Redactor.Redact(message));
if (exception is not null)
{
json.WriteString("error", Redactor.Redact(exception.GetType().Name + ": " + exception.Message));
json.WriteString("stack", Redactor.Redact(exception.StackTrace));
}
json.WriteEndObject();
}
var line = Encoding.UTF8.GetString(buffer.ToArray());
lock (_gate)
{
if (_console)
{
Console.Out.WriteLine(line);
}
WriteFile(now, line);
}
}
private void WriteFile(DateTimeOffset now, string line)
{
if (_folder is null)
{
return;
}
try
{
var day = now.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
if (_file is null || _fileDay != day)
{
_file?.Dispose();
Directory.CreateDirectory(_folder);
_file = new StreamWriter(new FileStream(Path.Combine(_folder, "anubis-" + day + ".log"), FileMode.Append, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete), new UTF8Encoding(false))
{
AutoFlush = true,
};
_fileDay = day;
Prune();
}
_file.WriteLine(line);
}
catch (IOException)
{
// A full or read-only disk must not stop the application: the console still has the line.
}
catch (UnauthorizedAccessException)
{
}
}
private void Prune()
{
foreach (var old in Directory.EnumerateFiles(_folder!, "anubis-*.log").OrderDescending(StringComparer.Ordinal).Skip(KeepFiles))
{
File.Delete(old);
}
}
public void Dispose()
{
lock (_gate)
{
_file?.Dispose();
_file = null;
}
}
private sealed class JsonLogger(string category, JsonLogProvider provider) : ILogger
{
public IDisposable? BeginScope<TState>(TState state)
where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}
provider.Write(category, logLevel, eventId, formatter(state, exception), exception);
}
}
}