背景
Avalonia 目前沒有富文字框可實現日誌輸出顯示,但提供了 SelectableTextBlock 控制項可以替代,這是站長實現的一個日誌元件效果:

可展示日誌時間、日誌級別、日誌詳細內容等,後台除輸出到介面外,也可持久化輸出到文字檔案,對於更多的日誌資訊展示可自行擴充,下面先講解實現過程,再指出存在的問題,歡迎 PR。
使用
安裝:
NuGet\Install-Package CodeWF.LogViewer.Avalonia -Version 1.0.10.2
檢視使用:
xmlns:log="https://codewf.com"
<log:LogView />
日誌輸出:
Logger.Debug("除錯日誌");
Logger.Info("資訊日誌");
Logger.Warn("警告日誌");
Logger.Error("錯誤日誌");
Logger.Fatal("致命日誌");
實現
只說關鍵部分程式碼,具體程式碼可瀏覽CodeWF.LogViewer倉庫。
程式透過 Logger 類別輸出日誌,該類別將日誌資訊快取到 ConcurrentQueue<LogInfo> Logs 集合,Logger 類別定義如下:
public static class Logger
{
public static LogType Level = LogType.Info;
public static string LogDir = AppDomain.CurrentDomain.BaseDirectory;
internal static readonly ConcurrentQueue<LogInfo> Logs = new();
public static void RecordToFile()
{
Task.Run(async () =>
{
while (true)
{
while (TryDequeue(out var log))
{
var content =
$"{log.RecordTime}: {log.Level.Description()} {log.Description}{Environment.NewLine}";
AddLogToFile(content);
}
await Task.Delay(TimeSpan.FromMilliseconds(100));
}
});
}
public static bool TryDequeue(out LogInfo info)
{
return Logs.TryDequeue(out info);
}
public static void Log(int type, string content)
{
var logType = (LogType)type;
if (Level > logType) return;
Logs.Enqueue(new LogInfo(logType, content));
}
public static void Debug(string content)
{
if (Level <= LogType.Debug)
{
Logs.Enqueue(new LogInfo(LogType.Debug, content));
}
}
public static void Info(string content)
{
if (Level <= LogType.Info)
{
Logs.Enqueue(new LogInfo(LogType.Info, content));
}
}
public static void Warn(string content)
{
if (Level <= LogType.Warn)
{
Logs.Enqueue(new LogInfo(LogType.Warn, content));
}
}
public static void Error(string content, Exception? ex = null)
{
if (Level > LogType.Error) return;
var msg = ex == null ? content : $"{content}\r\n{ex.ToString()}";
Logs.Enqueue(new LogInfo(LogType.Error, msg));
}
public static void Fatal(string content, Exception? ex = null)
{
if (Level > LogType.Fatal) return;
var msg = ex == null ? content : $"{content}\r\n{ex.ToString()}";
Logs.Enqueue(new LogInfo(LogType.Fatal, msg));
}
public static void AddLogToFile(string msg)
{
try
{
var logFolder = System.IO.Path.Combine(LogDir, "Log");
if (!Directory.Exists(logFolder))
{
Directory.CreateDirectory(logFolder);
}
var logFileName = System.IO.Path.Combine(logFolder, $"Log_{DateTime.Now:yyyy_MM_dd}.log");
File.AppendAllText(logFileName, msg);
}
catch
{
// ignored
}
}
}
只輸出日誌到文字檔案
如果只是輸出日誌到文字檔案,而不需要輸出到介面,需要主動呼叫 Logger.RecordToFile() 方法定時檢查日誌輸出。
同時輸出日誌到文字檔案和檢視
前提:這裡不需要呼叫 Logger.RecordToFile() 方法
我們先看檢視 LogView.axaml,該部分使用 ScrollViewer 包裹 SelectableTextBlock,以實現日誌滾動檢視及日誌文字的可選擇複製:
<ScrollViewer
x:Name="LogScrollViewer"
HorizontalScrollBarVisibility="Auto"
PointerPressed="LogScrollViewer_OnPointerPressed"
VerticalScrollBarVisibility="Auto">
<SelectableTextBlock
x:Name="LogTextView"
TextAlignment="Start"
TextWrapping="Wrap">
<SelectableTextBlock.ContextMenu>
<ContextMenu x:Name="LogContextMenu">
<MenuItem Click="Copy_OnClick" Header="複製" />
<MenuItem Click="Clear_OnClick" Header="清空" />
<MenuItem Click="Location_OnClick" Header="檢視日誌" />
</ContextMenu>
</SelectableTextBlock.ContextMenu>
</SelectableTextBlock>
</ScrollViewer>
LogView.axaml.cs 內呼叫 RecordLog() 方法定時讀取快取日誌,並再呼叫 LogNotifyHandler 方法寫入介面,及呼叫 Logger.AddLogToFile 方法寫入文字檔案,程式碼不多,下面是核心部分:
partial class LogView : UserControl
{
// ...
private void RecordLog()
{
if (_isRecording) return;
_isRecording = true;
Task.Run(async () =>
{
while (true)
{
while (Logger.TryDequeue(out var log)) LogNotifyHandler(log);
await Task.Delay(TimeSpan.FromMilliseconds(100));
}
});
}
private void LogNotifyHandler(LogInfo logInfo)
{
if (Logger.Level > logInfo.Level) return;
_synchronizationContext.Post(o =>
{
var inlines = _textView.Inlines;
try
{
if (inlines?.Count > MaxCount)
{
for (var i = 0; i < 3; i++)
{
var needRemoveElement = inlines.First();
if (needRemoveElement != null)
{
inlines.Remove(needRemoveElement);
}
}
}
var start = _textView.Text.Length;
inlines?.Add(
new Run($"{logInfo.RecordTime}")
{
Foreground = new SolidColorBrush(Color.Parse("#8C8C8C")),
BaselineAlignment = BaselineAlignment.Center
});
inlines?.Add(GetLevelInline(logInfo.Level));
inlines?.Add(new Run(logInfo.Description)
{
Foreground = new SolidColorBrush(Color.Parse("#262626")),
BaselineAlignment = BaselineAlignment.Center
});
inlines?.Add(new Run(Environment.NewLine));
Logger.AddLogToFile(
$"{logInfo.RecordTime}: {logInfo.Level.Description()} {logInfo.Description}{Environment.NewLine}");
_textView.SelectionStart = start;
_textView.SelectionEnd = _textView.Text.Length;
_scrollViewer.ScrollToEnd();
}
catch
{
// ignored
}
}, null);
}
private Span GetLevelInline(LogType level)
{
var content = level.Description();
// 建立寬度為零的透明文字,用於複製使用
// TODO:複製還是有問題,會錯位
var zeroWidthText = new Run($"【{content}】")
{
Foreground = Brushes.Transparent, FontSize = 0.001
};
// 視覺顯示的文字,不會被複製使用
var border = new Border
{
BorderBrush = GetLevelForeground(level),
Background = GetLevelBackground(level),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(2),
Padding = new Thickness(8, 0),
Margin = new Thickness(8, 2),
VerticalAlignment = VerticalAlignment.Center,
IsHitTestVisible = false,
Child = new TextBlock
{
Text = content,
Foreground = GetLevelForeground(level),
IsHitTestVisible = false
}
};
var levelSpan = new Span();
levelSpan.Inlines.Add(zeroWidthText);
levelSpan.Inlines.Add(border);
return levelSpan;
}
// ...
}
上面省略了根據日誌類型取得展示前景色、背景色等等程式碼,這不重要。
存在的問題
看上面的 GetLevelInline 方法,該方法產生日誌級別區塊,使用的 Border 套日誌級別描述(除錯、錯誤等),實現日誌類型帶邊框效果,但複製存在問題:

選擇的 7:56 除錯 模組 區塊並按 Ctrl + C 複製,再貼到記事本,複製出來是 除錯】模組名稱A-,很明顯的錯位問題。
複製的應該是文字內容,但 Border 是不允許複製的,所以程式碼中留了註解 建立寬度為零的透明文字,用於複製使用:
// 建立寬度為零的透明文字,用於複製使用
// TODO:複製還是有問題,會錯位
var zeroWidthText = new Run($"【{content}】")
{
Foreground = Brushes.Transparent, FontSize = 0.001
};
具體的不細說了,大家有什麼解決方案嗎?等待有緣人 PR 了,感謝。
總結
本文主要是尋求 PR,該元件如果對您有用,歡迎使用,倉庫地址:
- CodeWF.LogViewer:https://github.com/dotnet9/CodeWF.LogViewer
下篇分享自訂 TabItem 邊框實現:
