using MediaBrowser.Common.Kernel; using NLog; using NLog.Config; using NLog.Targets; using System.ComponentModel; using System.Threading; using System.Threading.Tasks; using System.Windows; namespace MediaBrowser.ServerApplication.Logging { /// /// Interaction logic for LogWindow.xaml /// public partial class LogWindow : Window { /// /// The _ui thread /// private readonly TaskScheduler _uiThread; /// /// The _kernel /// private readonly IKernel _kernel; /// /// Initializes a new instance of the class. /// /// The kernel. public LogWindow(IKernel kernel) { InitializeComponent(); _uiThread = TaskScheduler.FromCurrentSynchronizationContext(); _kernel = kernel; Loaded += LogWindow_Loaded; } /// /// Handles the Loaded event of the LogWindow control. /// /// The source of the event. /// The instance containing the event data. void LogWindow_Loaded(object sender, RoutedEventArgs e) { var target = new TraceTarget { Layout = "${longdate}, ${level}, ${logger}, ${message}" }; AddLogTarget(target, "LogWindowTraceTarget"); } /// /// Raises the event. /// /// A that contains the event data. protected override void OnClosing(CancelEventArgs e) { base.OnClosing(e); RemoveLogTarget("LogWindowTraceTarget"); } /// /// Logs the message. /// /// The MSG. public async void LogMessage(string msg) { await Task.Factory.StartNew(() => lbxLogData.Items.Insert(0, msg.TrimEnd('\n')), CancellationToken.None, TaskCreationOptions.None, _uiThread); } /// /// The log layout /// /// The log layout. public string LogLayout { get { return "${longdate}, ${level}, ${logger}, ${message}"; } } /// /// Adds the log target. /// /// The target. /// The name. private void AddLogTarget(Target target, string name) { var config = NLog.LogManager.Configuration; config.RemoveTarget(name); target.Name = name; config.AddTarget(name, target); var level = _kernel.Configuration.EnableDebugLevelLogging ? LogLevel.Debug : LogLevel.Info; var rule = new LoggingRule("*", level, target); config.LoggingRules.Add(rule); NLog.LogManager.Configuration = config; } /// /// Removes the log target. /// /// The name. private void RemoveLogTarget(string name) { var config = NLog.LogManager.Configuration; config.RemoveTarget(name); NLog.LogManager.Configuration = config; } /// /// Shuts down. /// public async void ShutDown() { await Task.Factory.StartNew(Close, CancellationToken.None, TaskCreationOptions.None, _uiThread); } } }