xihua475 发表于 2014-9-22 10:42:52

c#写日志类库【二尸兄】

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Reflection;

namespace CoreMes.Commom
{
    public class SysLog
    {
      public delegate void ExceptionHandler(string title, string info, bool IsTerminating);
      private static bool bool_0;
      private static bool bool_1;
      private static string _logpath;
      private static string _timeformat = "HH:mm:ss,fff";
      private static string apppath = null;
      private static Queue<string> queue_log = new Queue<string>();

      public static event ExceptionHandler NewLog;

      public static void BindExceptionLog()
      {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(SysLog.smethod_0);
            Application.ThreadException += new ThreadExceptionEventHandler(SysLog.smethod_1);
      }

      public static void RemoveExceptionLog()
      {
            AppDomain.CurrentDomain.UnhandledException -= new UnhandledExceptionEventHandler(SysLog.smethod_0);
            Application.ThreadException -= new ThreadExceptionEventHandler(SysLog.smethod_1);
      }

      private static void smethod_0(object sender, UnhandledExceptionEventArgs e)
      {
            StringBuilder builder = new StringBuilder();
            try
            {
                Exception exception = null;
                for (exception = (Exception)e.ExceptionObject; exception != null; exception = exception.InnerException)
                {
                  builder.AppendFormat("\r\n{0}\r\n{1}\r\n{2}", exception.GetType().FullName, exception.Message, exception.StackTrace);
                }
            }
            catch
            {
                builder.Append("\r\n记录本条日志时也出现异常,导致捕获的信息不完整...");
            }
            smethod_2("发现应用程序域中未被捕获的异常", builder.ToString());
            bool_0 = true;
            while (queue_log.Count > 0)
            {
                smethod_4(null);
                Thread.Sleep(100);
            }
            System.Diagnostics.Process.GetCurrentProcess().Kill();
      }

      private static void smethod_1(object sender, ThreadExceptionEventArgs e)
      {
            smethod_2("发现未被捕获的异常", string.Format("{0}\r\n{1}\r\n{2}", e.Exception.GetType().FullName, e.Exception.Message, e.Exception.StackTrace));
            bool_0 = true;
            while (queue_log.Count > 0)
            {
                smethod_4(null);
                Thread.Sleep(100);
            }
            System.Diagnostics.Process.GetCurrentProcess().Kill();
      }

      private static void smethod_2(string string_2, string string_3)
      {
            smethod_3(DateTime.Now, string_2, string_3);
            smethod_5(string_2, string_3, true);
      }

      private static void smethod_3(DateTime dateTime_0, string string_2, string string_3)
      {
            if (!bool_0)
            {
                string str;
                Monitor.Enter(str = "Lock");
                try
                {
                  queue_log.Enqueue("[" + dateTime_0.ToString(TimeFormat) + "]" + string_2 + "" + string_3 + Environment.NewLine);
                }
                catch
                {
                }
                finally
                {
                  Monitor.Exit(str);
                }
            }
      }

      private static void smethod_4(object object_0)
      {
            if (!bool_1)
            {
                bool_1 = true;
                string path = LogPath + @"\" + DateTime.Now.ToString("yyyyMMdd") + ".log";
                try
                {
                  using (StreamWriter writer = new StreamWriter(path, true, Encoding.Default))
                  {
                        while (queue_log.Count > 0)
                        {
                            string str2 = queue_log.Peek();
                            try
                            {
                              writer.Write(str2);
                              queue_log.Dequeue();
                              continue;
                            }
                            catch
                            {
                              break;
                            }
                        }
                        writer.Close();
                        writer.Dispose();
                  }
                }
                catch
                {
                }
                bool_1 = false;
            }
      }

      private static void smethod_5(string string_2, string string_3, bool bool_2)
      {
            if (NewLog != null)
            {
                NewLog(string_2, string_3, bool_2);
            }
      }

      public static string GetAppPath()
      {
            if (apppath == null)
            {
                Assembly executingAssembly = Assembly.GetExecutingAssembly();
                string location = executingAssembly.Location;
                apppath = location.Remove(location.Length - executingAssembly.ManifestModule.Name.Length);
            }
            return apppath;
      }

      
      public static void WriteLog(string title, string info)
      {
            smethod_3(DateTime.Now, title, info);
            ThreadPool.QueueUserWorkItem(new WaitCallback(SysLog.smethod_4));
            smethod_5(title, info, false);
      }

      public static string LogPath
      {
            get
            {
                if ((_logpath == null) || (_logpath.Length == 0))
                {
                  _logpath = GetAppPath() + "SysLog";
                }
                if (!Directory.Exists(_logpath))
                {
                  Directory.CreateDirectory(_logpath);
                }
                return _logpath;
            }
            set
            {
                _logpath = value;
            }
      }

      public static string TimeFormat
      {
            get
            {
                return _timeformat;
            }
            set
            {
                _timeformat = value;
            }
      }

    }
}

功能就是把信息写到本文文件中。
页: [1]
查看完整版本: c#写日志类库【二尸兄】