Skip to content

Instantly share code, notes, and snippets.

@Yuhanawa
Last active March 5, 2022 03:40
Show Gist options
  • Save Yuhanawa/5aa44c588cc7e817ddd40c81979906ad to your computer and use it in GitHub Desktop.
Save Yuhanawa/5aa44c588cc7e817ddd40c81979906ad to your computer and use it in GitHub Desktop.
Serilog.Sinks.WPF
using System.Windows;
using System.Windows.Controls;
using Serilog.Configuration;
using Serilog.Formatting.Display;
// ReSharper disable MemberCanBePrivate.Global
namespace Serilog.Sinks.WPF
{
public static class Extensions
{
/// <summary>
/// </summary>
/// <param name="configuration"></param>
/// <param name="outputTemplate"></param>
/// <returns></returns>
// ReSharper disable once InconsistentNaming
public static LoggerConfiguration WPF
(this LoggerSinkConfiguration configuration,
string outputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level:u4}] {Message:lj}{NewLine}{Exception}")
=> configuration.Sink(new LogEventSink(new MessageTemplateTextFormatter(outputTemplate)));
/// <summary>
/// </summary>
/// <param name="element">FrameworkElement</param>
/// <param name="ld">public delegate void LogDelegate(string msg)</param>
public static void ReceiveLog(this FrameworkElement element, LogEventSink.LogDelegate ld)
{
void TempLogReceived(string msg) => ld(msg);
element.Loaded += (_, _) => LogEventSink.LogReceived += TempLogReceived;
element.Unloaded += (_, _) => LogEventSink.LogReceived -= TempLogReceived;
}
/// <summary>
/// </summary>
/// <param name="element"></param>
public static void ReceiveLog(this TextBox element) =>
ReceiveLog(element, msg => element.Dispatcher.Invoke(() =>
{
element.AppendText(msg);
element.ScrollToEnd();
}));
/// <summary>
/// </summary>
/// <param name="element">RichTextBox</param>
public static void ReceiveLog(this RichTextBox element) =>
ReceiveLog(element, msg => element.Dispatcher.Invoke(() =>
{
element.AppendText(msg);
element.ScrollToEnd();
}));
/// <summary>
/// </summary>
/// <param name="element">TextBlock</param>
public static void ReceiveLog(this TextBlock element) =>
ReceiveLog(element, msg => element.Dispatcher.Invoke(() => { element.Text += msg; }));
}
}
using System.IO;
using Serilog.Core;
using Serilog.Events;
using Serilog.Formatting;
namespace Serilog.Sinks.WPF
{
public class LogEventSink : ILogEventSink
{
public LogEventSink(ITextFormatter formatter) => Formatter = formatter;
public delegate void LogDelegate(string msg);
public static event LogDelegate? LogReceived;
private ITextFormatter Formatter { get; }
public void Emit(LogEvent logEvent)
{
StringWriter stringWriter = new();
Formatter.Format(logEvent, stringWriter);
LogReceived?.Invoke(stringWriter.ToString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment