SystemLog.cs 2.51 KB
/// ----------------------------------------------------------------
/// 文 件 名:SystemLog.cs
/// 功能描述:系统错误日志类
/// 
/// 创建标识:杨斌 2011-11-29
/// ----------------------------------------------------------------
/// 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;

namespace GeneralLib
{
    /// <summary>
    /// 系统错误日志类
    /// </summary>
    public static class SystemLog
    {
        private static StreamWriter writerLog;

        public static string LogFile { get; set; }
        
        /// <summary>
        /// 将异常信息写入文件,并弹对话框
        /// </summary>
        /// <param name="exceptionTXT">异常对象</param>
        public static void WriterLog(Exception exceptionTXT, string msg="")
        {
            WriterLog(exceptionTXT, true, msg);
        }

        /// <summary>
        /// 将异常信息写入文件
        /// </summary>
        /// <param name="ex">异常对象</param>
        /// <param name="showMessageBox">是否弹对话框</param>
        public static void WriterLog(Exception ex, bool showMessageBox, string msg = "")
        {
            string title = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                    + " " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            
            string logInfo = DateTime.Now.ToString() + "\r\n" + title + "\r\n" + ex.ToString();
            if (!string.IsNullOrEmpty(msg))
                logInfo += msg;

            try//杨斌 2013-08-30
            {
                string logPath = LogFile + DateTime.Now.ToString("yyyyMMdd") + ".txt";

                if (showMessageBox)
                {
                    //MessageBox.Show(ex.ToString(), title);
                    new FrmErrorMsg(ex, logPath, msg).ShowDialog();
                }
                
                writerLog = File.AppendText(logPath);

                //if ((LogFile == null) || (LogFile.Length < 1))
                //    LogFile = new DirectoryInfo(GlobalInfo.GetAppWorkDir()).Parent.FullName;

                writerLog.WriteLine(logInfo);

                writerLog.Flush();
            }
            catch (System.Exception exWriterLog)
            {
                MessageBox.Show(exWriterLog.ToString(), title);
            }
            finally
            {
                writerLog.Close();
            }
        }       

    }
}