⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 zwavelogging.cs

📁 zwave 无线通讯协议 PC controller 控制器源码
💻 CS
字号:
//////////////////////////////////////////////////////////////////////////////////////////////// 
//
//          #######
//          #   ##    ####   #####    #####  ##  ##   #####
//             ##    ##  ##  ##  ##  ##      ##  ##  ##
//            ##  #  ######  ##  ##   ####   ##  ##   ####
//           ##  ##  ##      ##  ##      ##   #####      ##
//          #######   ####   ##  ##  #####       ##  #####
//                                           #####
//          Z-Wave, the wireless language.
//
//          Copyright Zensys A/S, 2005
//
//          All Rights Reserved
//
//          Description:   
//
//          Author:   Morten Damsgaard, Linkage A/S
//
//          Last Changed By:  $Author: jrm $
//          Revision:         $Revision: 1.4 $
//          Last Changed:     $Date: 2007/01/26 10:16:12 $
//
//////////////////////////////////////////////////////////////////////////////////////////////
#region Using directives

using System;
using System.Text;
using System.Diagnostics;
using System.Collections;
using System.IO;
using System.Threading;
using System.Globalization;
#endregion

namespace Zensys.ZWave.Logging
{
  /// <summary>
  /// Logging Class
  /// </summary>
  public class ZWaveLogging : IDisposable
  {
    private String module;
    private bool enable;

    static Hashtable logTable = new Hashtable(10);

    private string _logFilePath = "log.txt";
//#if !WIN_CE
    private string logFilePath {get {return _logFilePath;}}
    private string current_path { get { return ""; } }
/*#else
    private string _current_path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
    private string current_path { get { return _current_path; } }
    private string logFilePath { get { return _current_path + @"\" + _logFilePath;} }
#endif*/

    private Mutex mutexLog = new Mutex();
    private Mutex mutexFileLog = new Mutex();

    private long _logMaxSize = 1000000;
    /// <summary>
    /// Max size of the log file
    /// </summary>
    public long LogMaxSize {get {return _logMaxSize;} set{_logMaxSize = value;}}
    private FileInfo logFile;
    private bool disposed;
    /// <summary>
    /// Delegate for receiving text to write
    /// </summary>
    public delegate void LogEventHandler(string logString);
    /// <summary>
    /// Event Handler for receiving text to write
    /// </summary>
    public event LogEventHandler LogEvent;

    private bool writeCompleted = true;
    private Queue writeQueue = new Queue();
    private static bool FileCreated;
 
    private struct writeElement
    {
      public string str;
      public LogEventHandler handler;
    }

    /// <summary>
    /// Enabling module
    /// </summary>
    /// <param name="module"></param>
    /// <returns></returns>
    static public ZWaveLogging GetInstance(string module)
    {
      return GetInstance(module, true);
    }

    /// <summary>
    /// Enabling module
    /// </summary>
    /// <param name="module"></param>
    /// <param name="enable"></param>
    /// <returns></returns>
    static public ZWaveLogging GetInstance(string module, bool enable)
    {
      if (module == null)
      {
          throw new ArgumentNullException("module"); 
      }

      string toLowerText = module.ToLower(CultureInfo.CurrentCulture);    
      if (logTable.ContainsKey(toLowerText))
          return (ZWaveLogging)logTable[module.ToLower(CultureInfo.CurrentCulture)];
      ZWaveLogging log = new ZWaveLogging(module, enable);
      logTable.Add(module.ToLower(CultureInfo.CurrentCulture), log);
      return log;
    }

    /// <summary>
    /// Enable module
    /// </summary>
    /// <param name="module"></param>
    /// <param name="enable"></param>
    static public void EnableModule(string module, bool enable)
    {
      if (module == null)
      {
        throw new ArgumentNullException("module"); 
      } 
      if (logTable.ContainsKey(module.ToLower(CultureInfo.CurrentCulture)))
      {
        ZWaveLogging log = (ZWaveLogging)logTable[module.ToLower(CultureInfo.CurrentCulture)];
        log.Enable = enable;
      }
    }
 
    /// <summary>
    /// Enable frame and sessionlayer
    /// </summary>
    /// <param name="enable"></param>
    static public void EnableDebug(bool enable)
    {
      ZWaveLogging log = (ZWaveLogging)logTable["framelayer"];
      log.Enable = enable;
      log = (ZWaveLogging)logTable["sessionlayer"];
      log.Enable = enable;
    }

    private ZWaveLogging(string module, bool enable)
    {
      this.module = module;
      this.enable = enable;
      
      if (!FileCreated)
      {   
        logFile = new FileInfo(logFilePath);
        if (logFile.Exists)
        { 
          DateTime now = DateTime.Now;
          string savelog = string.Format(CultureInfo.InvariantCulture,"{0:00}-{1:00}-{2:00}_{3:00}_{4:00}.txt", now.Day,now.Month,now.Hour,now.Minute,now.Second);
            
          logFile.CopyTo(current_path + @"\" + savelog);
          logFile.Delete();  
        }
        this.LogEvent += new LogEventHandler(LogFileWrite); // Register logHandling function 
        FileCreated = true;
      }
    }

    /// <summary>
    /// Logging Class
    /// </summary>
    public ZWaveLogging()
    {
      logFile = new FileInfo(logFilePath);
      this.LogEvent += new LogEventHandler(LogFileWrite); // Register logHandling function 
    }

    /// <summary>
    /// Enable Properties
    /// </summary>
    public bool Enable
    {
      get
      {
        return enable;
      }  
      set
      {
        enable = value;
      }
    }

    /// <summary>
    /// Write text into logfile
    /// </summary>
    /// <param name="text"></param>
    public void Write(string text)
    {
        if (this.module != null)
        {
            if (!enable) return;
        }

        mutexLog.WaitOne();
        if (LogEvent != null)
        {
            StringBuilder sb = new StringBuilder(32);
            DateTime now = DateTime.Now;
            sb.Append(string.Format(CultureInfo.InvariantCulture, "{0:0000}{1:00}{2:00}-", now.Year, now.Month, now.Day));
            sb.Append(now.ToLongTimeString());
            sb.Append(".");
            sb.Append(string.Format(CultureInfo.InvariantCulture, "{0:000} ", now.Millisecond));
            sb.Append(text);
            writeElement el;
            el.str = sb.ToString();
            el.handler = null;
            foreach (LogEventHandler logHandle in LogEvent.GetInvocationList())
            {
                el.handler = logHandle;
                if (writeCompleted)
                {
                    writeCompleted = false;
#if !WIN_CE
                    //logHandle.BeginInvoke(el.str, new AsyncCallback(WriteCompleted), logHandle);
#else
                    //if we are in a Windows CE environment use the threadpool method to write
                    //asynchronously to the logfile
                    ThreadPool.QueueUserWorkItem(new WaitCallback(LogFileWrite), (object)el.str);
#endif
                }
                else
                {
                    writeQueue.Enqueue(el);
                }
            }
        }
        mutexLog.ReleaseMutex();
    }


#if !WIN_CE
    /// <summary>
    /// Callback for Write. Make sure that all Queued Writes are executed
    /// </summary>
    /// <param name="ar"></param>
    private void WriteCompleted(IAsyncResult ar)
    {
      LogEventHandler handle = (LogEventHandler)ar.AsyncState;
      handle.EndInvoke(ar);
      if(writeQueue.Count>0)
      {
        writeElement el = (writeElement )writeQueue.Dequeue();
        el.handler.BeginInvoke(el.str,new AsyncCallback(WriteCompleted),el.handler);
      }
      else
      {
        writeCompleted = true;
      }
    }
#endif

#if !WIN_CE
    /// <summary>
    /// Asynchronous method for writing to the log file
    /// </summary>
    /// <param name="logString">String to be logged</param>
    private void LogFileWrite(string logString)
    {
#else
    /// <summary>
    /// Asynchronous method for writing to the log file in WinCE. This method is executed when
    /// the next thread in the threadpool comes into context.
    /// </summary>
    /// <param name="logStr">Message to be written to the logfile</param>
    private void LogFileWrite(object logStr)
    {
          string logString = (string) logStr;
#endif
          mutexFileLog.WaitOne();
          logFile.Refresh();
          if (logFile.Exists)
          {
              if (logFile.Length >= LogMaxSize)
              {
                  string logBackup;
                  int delimiterIndex;
                  int extensionLen;
                  try
                  {
                      delimiterIndex = logFilePath.LastIndexOf('.');
                      if (delimiterIndex > 0)
                      {
                          extensionLen = logFilePath.Length - delimiterIndex;
                          logBackup = logFilePath.Substring(0, delimiterIndex) + "_"
                            + logFilePath.Substring(delimiterIndex, extensionLen);
                      }
                      else
                      {
                          DateTime now = DateTime.Now;
                          string text = string.Format(CultureInfo.InvariantCulture, "{0}{1:00}{2:00}-{3:00}{4:00}", now.Year, now.Month, now.Day, now.Hour, now.Minute);
                          logBackup = logFilePath + "_" + text;
                      }
                      File.Move(logFilePath, logBackup);
                  }
                  catch
                  {
                      File.Delete(logFilePath);
                      throw;
                  }
              }
          }
          FileStream fs = new FileStream(logFilePath, FileMode.Append, FileAccess.Write);
          StreamWriter w = new StreamWriter(fs);
          w.WriteLine(logString);
          w.Flush();
          w.Close();
          mutexFileLog.ReleaseMutex();

#if WIN_CE
          //check if there is anything else in the queue. If there is queue it using the threadpool
          if (writeQueue.Count > 0)
          {
              writeElement el = (writeElement)writeQueue.Dequeue();
              ThreadPool.QueueUserWorkItem(new WaitCallback(LogFileWrite), (object)el.str);
          }
          //if not indicate that writing to the logfile is completed
          else
          {
              writeCompleted = true;
          }
#endif
    }



    /// <summary>
    /// Creates a backup copy of logfile in the path given
    /// </summary>
    /// <param name="path">path to copy log to</param>
    public void Backup(string path)
    {      
      if (!Directory.Exists(path))
      {
          try
          {
              Directory.CreateDirectory(path);
          }
          catch
          {
            Console.WriteLine("Failed to create backup directory");
            throw;
          }    
      }
      StringBuilder dst = new StringBuilder();
      dst.Append(path);
      dst.Append("\\");
      dst.Append(logFilePath);
      File.Copy(logFilePath,dst.ToString());
    }

    /// <summary>
    /// Dispose
    /// </summary>
    public void Dispose()
    {
      Dispose(true);
    }

    /// <summary>
    /// Dispose
    /// </summary>
    protected virtual void Dispose(bool disposing)
    {
      if (!disposed)
      {
        disposed = true;

        if (disposing)
        {
          mutexLog.Close();
          GC.SuppressFinalize(this);
        }
      }
    }

  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -