Exemple #1
0
        /// <summary>
        /// 输出日志,可以指定是否缓存
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="issave"></param>
        public static void WriteLog(string msg, bool issave)
        {
            // 增加线程锁。在多线程环境下,StringBuilder.Append方法有时会抛出System.ArgumentOutOfRangeException异常,导致软件崩溃。
            if (Monitor.TryEnter(ThreadLock, 3000))
            {
                try
                {
                    sb.AppendLine(Tools.GetDateTimeNowString());
                    sb.AppendLine(msg).AppendLine();

                    if (sb.Length > 1000 || issave)
                    {
                        string       fileName = LogFile;
                        FileInfo     file     = new FileInfo(fileName);
                        StreamWriter w        = new StreamWriter(file.FullName, true, System.Text.Encoding.UTF8);
                        w.Write(sb.ToString());
                        w.Flush();
                        w.Close();
                        w  = null;
                        sb = new StringBuilder();
                    }
                }
                catch (ArgumentOutOfRangeException)
                {
                    //有时在写日志到文件中时会出现异常System.ArgumentOutOfRangeException,导致软件崩溃
                    //因此当出现异常时,把之前的日志抛弃掉,以防日志过长
                    sb = new StringBuilder();
                }
                catch (Exception)
                {
                }
                finally
                {
                    Monitor.Exit(ThreadLock);
                }
            }
        }