码迷,mamicode.com
首页 > Windows程序 > 详细

C#简单写日志

时间:2018-07-01 21:20:47      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:文件   targe   write   names   sts   create   startup   out   写入   

自己整理了一个简单写日志的类,方便以后再次用到。

说明:CS程序,程序启动目录下,自动创建Log目录,写日志。日志按天记录,每天的日志作为一个txt文件保存。

 /// <summary>
    /// 日志管理功能
    ///  //以天建立日志文件,
    /// </summary>
    public class LogManager
    {
        private static string LogDirectory = Application.StartupPath + @"\Log\";

        /// <summary>
        /// 保存的最多日志数量
        /// </summary>
        private static int MaxLogCount = 365;

        public static void Write(string msg)
        {
            try
            {
                DeleteLog();
                if (!System.IO.Directory.Exists(LogDirectory))
                {
                    System.IO.Directory.CreateDirectory(LogDirectory);
                }
                string name = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, ‘0‘) + DateTime.Now.Day.ToString().PadLeft(2, ‘0‘);
                string datapath = LogDirectory + name + ".txt";
                if (System.IO.File.Exists(datapath))//追加
                {
                    using (FileStream fs = new FileStream(datapath, FileMode.Append))
                    { 
                        using (StreamWriter sw = new StreamWriter(fs))
                        {
                            //开始写入
                            sw.WriteLine("\n");
                            sw.WriteLine("当前时间:" + DateTime.Now.ToString());
                            sw.WriteLine("日志信息:" + msg);
                            //清空缓冲区
                            sw.Flush();
                            //关闭流
                            sw.Close();
                            fs.Close();
                        }
                    }
                }
                else//创建
                {
                    using (FileStream fs = new FileStream(datapath, FileMode.Create))
                    {
                        using (StreamWriter sw = new StreamWriter(fs))
                        {
                            //开始写入
                            sw.WriteLine("当前时间:" + DateTime.Now.ToString());
                            sw.WriteLine("日志信息:" + msg);
                            //清空缓冲区
                            sw.Flush();
                            //关闭流
                            sw.Close();
                            fs.Close();
                        }
                    }
                }
            }
            catch
            {

            }


        }

        public static void Write(Exception ex)
        {
            try
            {
                DeleteLog();
                if (!System.IO.Directory.Exists(LogDirectory))
                {
                    System.IO.Directory.CreateDirectory(LogDirectory);
                }
                string name = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, ‘0‘) + DateTime.Now.Day.ToString().PadLeft(2, ‘0‘);
                string datapath = LogDirectory + name + ".txt";//文件名格式为:20170606.txt
                if (System.IO.File.Exists(datapath))//追加
                {
                    using (FileStream fs = new FileStream(datapath, FileMode.Append))
                    {
                        using (StreamWriter sw = new StreamWriter(fs))
                        { //开始写入
                            sw.WriteLine("\n");
                            sw.WriteLine("当前时间:" + DateTime.Now.ToString());
                            sw.WriteLine("异常信息:" + ex.Message);
                            sw.WriteLine("异常对象:" + ex.Source);
                            sw.WriteLine("调用堆栈:" + ex.StackTrace);
                            sw.WriteLine("触发方法:" + ex.TargetSite);
                            //清空缓冲区
                            sw.Flush();
                            //关闭流
                            sw.Close();
                            fs.Close();
                        }
                    }
                }
                else//创建
                {
                    using (FileStream fs = new FileStream(datapath, FileMode.Create))
                    {
                        using (StreamWriter sw = new StreamWriter(fs))
                        {
                            //开始写入
                            sw.WriteLine("当前时间:" + DateTime.Now.ToString());
                            sw.WriteLine("异常信息:" + ex.Message);
                            sw.WriteLine("异常对象:" + ex.Source);
                            sw.WriteLine("调用堆栈:" + ex.StackTrace);
                            sw.WriteLine("触发方法:" + ex.TargetSite);
                            //清空缓冲区
                            sw.Flush();
                            //关闭流
                            sw.Close();
                            fs.Close();
                        }
                    }
                }
            }
            catch
            {

            }

        }

        /// <summary>
        /// 删除日志
        /// </summary>
        private static void DeleteLog()
        {
            DirectoryInfo dic = new DirectoryInfo(LogDirectory);

            //不必每天都删除日志,整10天删除
            if (!(DateTime.Now.Day % 10 == 0))
            {
                return;
            }

            if (dic.Exists)
            {
                var files = dic.GetFiles();
                if (files.Length < MaxLogCount)
                    return;

                List<int> names = new List<int>();
                for (int i = 0; i < files.Length; i++)
                {
                    string strname = Path.GetFileNameWithoutExtension(files[i].Name);
                    int name;
                    if (int.TryParse(strname, out name))
                    {
                        names.Add(name);
                    }
                }

                names.Sort();//升序
                //names.Reverse();//降序

                for (int i = 0; i < names.Count - MaxLogCount; i++)
                {
                    string path = System.IO.Path.Combine(LogDirectory, names[i].ToString() + ".txt");
                    File.Delete(path);
                }


            }
        }




    }

  

C#简单写日志

标签:文件   targe   write   names   sts   create   startup   out   写入   

原文地址:https://www.cnblogs.com/zwcoding/p/9251273.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!