写日志的简单方法,临时用用很方便

public static void WriteLog(string msg)
        {
            FileStream fs = null;
            StreamWriter sw = null;

            try
            {
                var basePath = AppDomain.CurrentDomain.BaseDirectory;
                if (!basePath.EndsWith("/"))
                    basePath += "/";

                var logFile = basePath + DateTime.Now.ToString("yyyyMMdd") + "_debug.log";
                if (!File.Exists(logFile))
                    File.CreateText(logFile).Dispose();

                fs = new FileStream(logFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                sw = new StreamWriter(fs, Encoding.UTF8);

                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.fff"));
                sw.WriteLine(msg);
                sw.WriteLine("-------------------------------------");
                sw.Flush();
                fs.Flush();
            }
            catch { }
            finally
            {
                if (sw != null)
                {
                    try { sw.Close(); sw.Dispose(); } catch { }
                }
                if (fs != null)
                {
                    try { fs.Close(); fs.Dispose(); } catch { }
                }
            }
        }

猜你喜欢

转载自www.cnblogs.com/itjeff/p/10536096.html
今日推荐