86 lines
2.7 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Diagnostics;
using System.Text;
using NLog;
using Prism.Events;
using Prism.Regions;
using RIZO_Application.Core;
using RIZO_Application.Core.Mvvm;
namespace RIZO_Application.Modules.LogModule.ViewModels
{
public class SystemLogViewModel : RegionViewModelBase
{
private readonly IEventAggregator _eventAggregator;
private SubscriptionToken _token;
private readonly StringBuilder _logMessageBuilder = new StringBuilder();
private Logger _logger = LogManager.GetCurrentClassLogger();
private const int MaxLogLength = 1000; // 假设最大长度为1000可以根据实际情况调整
private const string LogFormat = "\n{0}: {1}";
// 定义一个日志更新事件
public event EventHandler LogUpdated;
public string LogMessage
{
get { return _logMessageBuilder.ToString(); }
set
{
_logMessageBuilder.Clear();
_logMessageBuilder.Append(value);
RaisePropertyChanged(nameof(LogMessage));
}
}
public SystemLogViewModel(
IRegionManager regionManager,
IEventAggregator eventAggregator)
: base(regionManager)
{
OnLogReceived("初始化日志系统");
_eventAggregator = eventAggregator;
// 订阅事件使用UI线程处理保持强引用
_token = _eventAggregator.GetEvent<SystemLogEvent>().Subscribe(OnLogReceived, ThreadOption.UIThread, true);
}
private void OnLogReceived(string message)
{
string newLog = string.Format(LogFormat, DateTime.Now, message);
_logMessageBuilder.Append(newLog);
if (_logMessageBuilder.Length > MaxLogLength)
{
// 计算需要截取的位置,保留最新的日志
int startIndex = Math.Max(0, _logMessageBuilder.Length - MaxLogLength);
_logMessageBuilder.Remove(0, startIndex);
}
RaisePropertyChanged(nameof(LogMessage));
_logger.Info(newLog);
// 触发日志更新事件
OnLogUpdated();
}
protected virtual void OnLogUpdated()
{
LogUpdated?.Invoke(this, EventArgs.Empty);
}
public void Destroy()
{
_token?.Dispose();
}
public void AddTestLogMessage()
{
// 示例实现,可根据需求修改
OnLogReceived("测试日志消息");
}
public override void OnNavigatedTo(NavigationContext navigationContext)
{
//do something
}
}
}