<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<!-- ===================================================================================== -->
<!-- optional, add some variables -->
<!-- ===================================================================================== -->
<variable name="myvar" value="myvalue"/>
<variable name="variable1" value="${basedir}/logs"/>
<!-- ===================================================================================== -->
<!-- See https://github.com/nlog/nlog/wiki/Configuration-file for information on customizing logging rules and outputs. -->
<!-- ===================================================================================== -->
<targets>
<target name="LogFileManager" xsi:type="File"
fileName="${basedir}/logs/Manager/${shortdate}.log"
archiveFileName="${basedir}/logs/Manager/Archives/${shortdate}.{#####}.log"
archiveNumbering="Sequence"
archiveAboveSize="5242880"
maxArchiveFiles="0"
keepFileOpen="false"
concurrentWrites="false"
layout ="${time} [${pad:padding=5:inner=${level:uppercase=true:format=Name}}] ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}"
encoding="utf-8"
/>
<target name="LogTextManager" xsi:type="TextBox"
layout ="${time} [${pad:padding=5:inner=${level:uppercase=true:format=Name}}] ${message} ${newline}"
WindowName="MainWindow"
ControlName="RunLog"
MaxLines="100"/>
</targets>
<!-- ===================================================================================== -->
<!-- See https://github.com/nlog/nlog/wiki/Configuration-file for information on customizing logging rules and outputs. -->
<!-- ===================================================================================== -->
<rules>
<logger name="Manager" minlevel="Debug" writeTo="LogTextManager,LogFileManager"/>
</rules>
</nlog>
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using NLog.Targets;
namespace NLog.Windows.Wpf
{
[Target("TextBox")]
public sealed class TextBoxTarget : TargetWithLayout
{
private int _maxLines = 50;
public TextBox TargetTextBox;
/// <summary>
/// 显示日志的控件名称
/// </summary>
public string ControlName { get; set; }
/// <summary>
/// 包含显示日志控件的窗口的名称
/// </summary>
public string WindowName { get; set; }
/// <summary>
/// 显示控件中最多存储多少行日志
/// </summary>
public int MaxLines
{
get => _maxLines;
set
{
if (value < 50) value = 50;
if (value > 500) value = 500;
_maxLines = value;
}
}
public static void ReInitializeTarget(Window window)
{
foreach (var item in LogManager.Configuration.AllTargets)
{
if (!(item is TextBoxTarget target) || target.WindowName != window.Title) continue;
if (string.IsNullOrEmpty(target.WindowName) || string.IsNullOrWhiteSpace(target.WindowName))
{
MessageBox.Show(
"The param of WindowName is set to null, empty or whitespace, please correct it.");
return;
}
if (string.IsNullOrEmpty(target.ControlName) || string.IsNullOrWhiteSpace(target.ControlName))
{
MessageBox.Show(
"The param of ControlName is set to null, empty or whitespace, please correct it.");
return;
}
// 根据窗口名查找窗口
Window parentWindowOfTextBox = null;
foreach (Window win in Application.Current.Windows)
if (win.DependencyObjectType.Name == target.WindowName)
parentWindowOfTextBox = window;
if (parentWindowOfTextBox == null)
{
MessageBox.Show($"Can not find the window that is named {target.WindowName}, please correct it.");
return;
}
// 根据控件名在指定的窗口中查找控件
target.TargetTextBox = GetChildByName<TextBox>((DependencyObject)parentWindowOfTextBox.Content, target.ControlName);
if (target.TargetTextBox == null)
MessageBox.Show($"Can not find the TextBox that is named {target.ControlName}, please correct it.");
target.InitializeTarget();
return;
}
}
protected override void InitializeTarget()
{
base.InitializeTarget();
if (TargetTextBox == null)
return;
// 设置控件属性
TargetTextBox.FontSize = 16;
TargetTextBox.Padding = new Thickness(5);
TargetTextBox.FontFamily = new FontFamily("Courier New");
// 鼠标双击事件
TargetTextBox.MouseDoubleClick += (sender, e) => { TargetTextBox.Clear(); };
}
/// <summary>
/// </summary>
/// <param name="logEvent"></param>
protected override void Write(LogEventInfo logEvent)
{
TargetTextBox?.Dispatcher?.BeginInvoke(new Action<string>(SendToTextBox),Layout.Render(logEvent));
}
private void SendToTextBox(string logMessage)
{
if (TargetTextBox.LineCount > _maxLines)
TargetTextBox.Clear();
TargetTextBox.AppendText(logMessage);
TargetTextBox.ScrollToEnd();
}
private static T GetChildByName<T>(DependencyObject obj, string elementName) where T : FrameworkElement
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
var child = VisualTreeHelper.GetChild(obj, i);
if (child is T element && element.Name == elementName)
return element;
var grandChild = GetChildByName<T>(child, elementName);
if (grandChild != null)
return grandChild;
}
return null;
}
}
}
使用方法:
public static Logger LogHelper;
public MainWindow()
{
InitializeComponent();
NLog.Windows.Wpf.TextBoxTarget.ReInitializeTarget(this);
LogHelper = LogManager.GetLogger("Manager");
}