using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Mall.WindowsService.Helper
{
    /// <summary>
    /// 日志帮助类
    /// </summary>
    public class LogHelper
    {
        /// <summary>
        /// 防止多线程
        /// </summary>
        private static object objlock = new object();

        public static string filepath = string.Format(@"{0}\Log", PathHelper.RootPath);

        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="path"></param>
        private static void CreateDirectory(string path)
        {
            //创建文件夹
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="message">日志信息</param>
        /// <returns></returns>
        public static void Write(string message)
        {
            CreateDirectory(filepath);
            string FileName = string.Format(@"{0}\{1}.txt", filepath, DateTime.Now.ToString("yyyyMMdd"));
            lock (objlock)
            {
                using (StreamWriter sw = File.AppendText(FileName))
                {
                    sw.WriteLine(string.Format(@"DateTime:{0} ", DateTime.Now.ToString()));
                    sw.WriteLine(string.Format(@"Message:{0}", message));
                }
            }
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="exception">异常信息</param>
        /// <param name="otherMsg">其他信息</param>
        public static void WriteLog(Exception exception, string otherMsg = "")
        {
            CreateDirectory(filepath);
            string str = "";
            try
            {
                str += string.Format(@"
DateTime:{0}", DateTime.Now.ToString());
                if (exception != null)
                {
                    if (exception.InnerException != null)
                    {
                        exception = exception.InnerException;
                    }
                    str += string.Format(@"
Message:{0}
StackTrace:
{1}
Source:{2}
", exception.Message
 , exception.StackTrace
 , exception.Source

                    );
                }
                str += string.Format(@"
ExtMessage:{0}", otherMsg);
                string FileName = string.Format(@"{0}\{1}.txt", filepath, DateTime.Now.ToString("yyyyMMdd"));

                lock (objlock)
                {
                    StreamWriter sw = new StreamWriter(FileName, true);
                    sw.WriteLine(str);
                    sw.Close();
                }
            }
            catch
            {

            }
        }
    }
}
