using System;
using System.IO;
using System.Threading.Tasks;

namespace Mall.IM.Util
{
    public class LogHelper
    {
        private static object objlock = new object();
        /// <summary>
        /// 日志保存路径
        /// </summary>
        public static string LogPath
        {
            get
            {
                string logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log");
                return logPath.ToString();
            }
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="ex"></param>
        public static void Write(Exception ex)
        {
            Write(ex, "");
        }

        /// <summary>
        /// 写日志信息
        /// </summary>
        /// <param name="exception"></param>
        /// <param name="otherMsg"></param>
        public static void Write(Exception exception, string otherMsg)
        {
            Task.Run(() => WriteLog(exception, otherMsg));
        }

        /// <summary>
        /// 写日志信息具体方法
        /// </summary>
        /// <param name="exception">异常信息</param>
        /// <param name="otherMsg">其他信息</param>
        private static void WriteLog(Exception exception, string otherMsg)
        {
            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 logdir = LogPath;
                if (!Directory.Exists(logdir))
                    Directory.CreateDirectory(logdir);

                string filePath = Path.Combine(logdir, DateTime.Now.ToString("yyyyMMdd") + ".txt");

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

            }
        }
    }
}
