【NLog】【TextBoxTarget】

<?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");
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhy29563

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值