C# 实现一个Log日志文件 以每2Mb创建一个新的日志

本文详细介绍了如何在程序中实现日志文件的管理与操作,包括日志路径设置、文件创建、日志大小限制及日志内容的写入等关键步骤。

 

这个日志文件存放在程序的bin文件夹下得Debug中

static private string logpathlog = AppDomain.CurrentDomain.BaseDirectory + "log.txt";

        static public void writelog(string classname)
        {
            string path = logpathlog;
            if (!File.Exists(path))
            {
                // Create a file to write to.
                using (File.Create(path)) { }
            }

            FileInfo fileinfo = new FileInfo(path);
            if (fileinfo.Length > 1024 * 1024 * 2)
            {
                File.Move(path, AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.ToString("yyyyMMddHHmmss") + "log.txt");

                if (!File.Exists(path))
                {
                    using (File.Create(path)) { }
                }

            }

            using (StreamWriter sw = File.AppendText(path))
            {
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + "\t\n");
                sw.WriteLine(classname + "\t\n");
                sw.WriteLine("------------------------------------------------------------------------" + "\t\n");
                sw.Close();
            }

        }


 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值