winform C# 存储log捕获异常

    static class Program
    {
        /// 
        /// 应用程序的主入口点。
        /// 
        [STAThread]
        static void Main()
        {
            SetTrace();
            //处理未捕获的异常
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            //处理UI线程异常
            Application.ThreadException += Application_ThreadException;
            //处理非UI线程异常
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            Trace.WriteLine(e.Exception.StackTrace);
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Trace.WriteLine(e.ExceptionObject);
        }

        /// 
        /// 配置 System.Diagnostics.Trace,这样就可以通过 Trace.WriteLine() 存储日志
        /// 
        public static void SetTrace()
        {
            string logDir = "Logs";
            if (!Directory.Exists(logDir))
            {
                Directory.CreateDirectory(logDir);
            }
            Trace.AutoFlush = true;
            // Clear the default listener
            Trace.Listeners.Clear();
            // Add a writer that appends to the txt file
            Trace.Listeners.Add(new TextWriterTraceListener($"{logDir}/trace-{DateTime.Now:yyyyMMdd}.txt"));
            // Obtain the Console's output stream, then add that as a listener
            Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
        }
    }

你可能感兴趣的:(Windows桌面应用,c#,windows)