C# 日志记录文件当满2M自动创建新日志文件

1,创建简单的错误日志文件,以当前日期为文件名

public static void WriteLog(string str)
{
if (!Directory.Exists("ErrLog"))
{
Directory.CreateDirectory("ErrLog");
}

using (var sw = new StreamWriter(@"ErrLog\"+ DateTime.Now.ToString("yyyy-MM-dd")+".txt", true))
{
sw.WriteLine(str); 
sw.Close();
}
}

2,创建日志文件,当日志文件满2M时自动创建新日志文件

string fullpath = @"Log\InfoLog\" + DateTime.Now.ToString("yyyy-MM-dd") + @"\Log.txt";
       CommonLog(i + "log", fullpath);
string path = @"Log\ErrLog\" + DateTime.Now.ToString("yyyy-MM") + @"\Err.txt";
        CommonLog(i + "log", path);
        i++;

 

public static void CommonLog(string message, string fullpath)
        {
            //文件所在路径
            string logpath = Path.GetDirectoryName(fullpath);
            //文件名称
            string filename = Path.GetFileNameWithoutExtension(fullpath);

            if (!Directory.Exists(logpath))
            {
                Directory.CreateDirectory(logpath);
            }
            if (!File.Exists(fullpath))
            {
                using (File.Create(fullpath)) { }
            }
            FileInfo fileinfo = new FileInfo(fullpath);
            //获取指定目录下的所有的子文件
            string[] files = Directory.GetFiles(logpath, filename + "*", SearchOption.TopDirectoryOnly);
            //if (fileinfo.Length > 2 * 1024 * 1024)
            if (fileinfo.Length > 2 * 1024)
            {
                File.Move(fullpath, GetPathStr(logpath, string.Format("{0}.log", filename + files.Length)));

                if (!File.Exists(fullpath))
                {
                    using (File.Create(fullpath)) { }
                }
            }
            using (StreamWriter sw = File.AppendText(fullpath))
            {
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "" + "\t\n");
                sw.WriteLine("-----------------------" + "\t\n");
                sw.WriteLine("Message :" + message + "\t\n");
                sw.WriteLine("====================================================================" + "\t\n\t\n\t\n");
                sw.Close();
            }
        }
            /// <summary>
            /// 拼接地址串
            /// </summary>
            /// <param name="firstPath"></param>
            /// <param name="secondPath"></param>
            /// <returns></returns>
            private static string GetPathStr(string firstPath, string secondPath)
        {
            StringBuilder builder = new StringBuilder();

            builder.Append(firstPath);
            builder.Append("\\");
            builder.Append(secondPath);
            return builder.ToString();
        }

 

posted on 2021-05-25 11:04  沫丶灬沫  阅读(460)  评论(0编辑  收藏  举报