在WPF中,使用控制台输出日志信息

一、背景

之前的项目中,使用Log4NET将日志信息输出到文本文件中。这种方法适用于常看以前的日志信息,却并不适用于实时查看日志。本以为Log4NET可以很方便地通过配置appender来解决这个问题。无奈,个人水平有限,只能够在控制台程序中实现,而在WPF应用中没有解决这个问题。后来将解决方案转win32。通过调用win32函数来直接输出信息到控制台。

二、解决方案

帮助类

    public class ConsoleLogHelper
    {

        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("kernel32", CharSet = CharSet.Auto)]
        internal static extern bool AllocConsole();

        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("kernel32", CharSet = CharSet.Auto)]
        internal static extern bool FreeConsole();

        /// 
        /// 在程序启动时,执行一次即可
        /// 
        public static void OpenConsole()
        {
            try
            {
                var consoleTitle = "App Runtime Log";
                AllocConsole();
                Console.BackgroundColor = ConsoleColor.Black;

                Console.CursorVisible = false;
                Console.Title = consoleTitle;
            }
            catch (Exception)
            {
                throw;
            }
        }


        /// 
        /// 该方法只在退出程序时,调用
        /// 
        public static void CloseConsole()
        {
            FreeConsole();
        }

        public static void WriteLine(string msg)
        {
            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            Console.WriteLine(msg);
            Console.ForegroundColor = ConsoleColor.White;
        }
        public static void WriteLineError(string msg)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            WriteLine(msg);
        }

        public static void WriteLineError(Exception ex)
        {
            WriteLineError(ex.Message);
        }

        public static void WriteLineInfo(string msg)
        {
            Console.ForegroundColor = ConsoleColor.Cyan;
            WriteLine(msg);
        }

    }

使用 App.cs

    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            ConsoleLogHelper.OpenConsole();
        }

        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);
            ConsoleLogHelper.CloseConsole();
        }
    }

使用 MainWindow.xaml

<Window x:Class="Log4Net_Appender_Console.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Log4Net_Appender_Console"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel>
            <Button Click="Button_Click_default"
                    Width="200"
                    Height="50">defaultButton>
            <Button Click="Button_Click_error"
                    Width="200"
                    Height="50">errorButton>
            <Button Click="Button_Click_exception"
                    Width="200"
                    Height="50">exceptionButton>
            <Button Click="Button_Click_info"
                    Width="200"
                    Height="50">infoButton>

        StackPanel>

    Grid>
Window>

使用 MainWindow.cs

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Excute(Action<int> action)
        {
            for (int i = 0; i < 10; i++)
            {
                action(i);
            }
        }

        private void Button_Click_default(object sender, RoutedEventArgs e)
        {
            Excute((i)=> {
                Console.WriteLine($"default-->{i.ToString()}");
            });
        }

        private void Button_Click_error(object sender, RoutedEventArgs e)
        {
            Excute((i) => {
                ConsoleLogHelper.WriteLineError($"error-->{i.ToString()}");
            });
        }

        private void Button_Click_exception(object sender, RoutedEventArgs e)
        {
            try
            {
                string a = null;
                a.ToString();
            }
            catch (Exception ex)
            {
                Excute((i) => {
                    ConsoleLogHelper.WriteLineError(ex);
                });
            }
        }

        private void Button_Click_info(object sender, RoutedEventArgs e)
        {
            Excute((i) => {
                ConsoleLogHelper.WriteLineInfo($"info-->{i.ToString()}");
            });
        }
    }

三、分析

使用核心函数AllocConsole()在当前线程中打开一个控制台。然后使用Console.WriteLine()将信息输出到控制台。

你可能感兴趣的:(WPF)