log to hutao

This commit is contained in:
DismissedLight
2024-10-21 17:01:26 +08:00
committed by qhy040404
parent d41b6f0573
commit 2e0c215b87
4 changed files with 55 additions and 4 deletions

View File

@@ -69,6 +69,7 @@ public partial class App : Application
{
loggerConfiguration.WriteTo.RichTextBox(richTextBox, LogEventLevel.Information, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}");
}
loggerConfiguration.WriteTo.Sink(new HutaoNamedPipeLogEventSink(), LogEventLevel.Information);
Log.Logger = loggerConfiguration.CreateLogger();
services.AddLogging(c => c.AddSerilog());

View File

@@ -92,6 +92,10 @@ internal sealed partial class BGINamedPipe : IDisposable
}
break;
case (PipePacketType.SessionTermination, _):
serverStream.Disconnect();
return;
}
}
}

View File

@@ -1,9 +1,6 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System;
using System.IO.Pipes;
using System.Text;
using System.Text.Json.Serialization;
namespace BetterGenshinImpact.Hutao;
@@ -40,6 +37,18 @@ internal sealed partial class HutaoNamedPipe : IDisposable
get => isSupported.Value;
}
public bool TryRedirectLog(string log)
{
if (!IsSupported)
{
return false;
}
byte[] buffer = Encoding.UTF8.GetBytes(log);
clientStream.Write(buffer, 0, buffer.Length);
return true;
}
public void Dispose()
{
clientStream.Dispose();

View File

@@ -0,0 +1,37 @@
using Serilog.Core;
using Serilog.Events;
using Serilog.Formatting.Display;
using System.IO;
namespace BetterGenshinImpact.Hutao;
internal sealed class HutaoNamedPipeLogEventSink : ILogEventSink
{
private readonly MessageTemplateTextFormatter textFormatter = new("[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}");
private readonly MemoryStream buffer;
private readonly TextWriter writer;
private readonly TextReader reader;
private HutaoNamedPipe? namedPipe;
public HutaoNamedPipeLogEventSink()
{
buffer = new();
writer = new StreamWriter(buffer);
reader = new StreamReader(buffer);
}
private HutaoNamedPipe NamedPipe
{
get => namedPipe ??= App.GetService<HutaoNamedPipe>()!;
}
public void Emit(LogEvent logEvent)
{
textFormatter.Format(logEvent, writer);
buffer.Position = 0;
NamedPipe.TryRedirectLog(reader.ReadToEnd());
buffer.SetLength(0);
}
}