C#简单写日志
来源:互联网 发布:如何计算矩阵的行列式 编辑:程序博客网 时间:2024/06/04 19:26
自己整理了一个简单写日志的类,方便以后再次用到。
说明:CS程序,程序启动目录下,自动创建Log目录,写日志。日志按天记录,每天的日志作为一个txt文件保存。
/// <summary> /// 日志管理功能 /// </summary> public class LogManager { private static string logdirectory = Application.StartupPath + @"\Log\"; public static void Write(string msg) { 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)) { 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)) { StreamWriter sw = new StreamWriter(fs); //开始写入 sw.WriteLine("当前时间:" + DateTime.Now.ToString()); sw.WriteLine("日志信息:" + msg); //清空缓冲区 sw.Flush(); //关闭流 sw.Close(); fs.Close(); } } } public static void Write(Exception ex) { 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)) { 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)) { 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(); } } } }
阅读全文
0 0
- C#简单写日志
- C# 简单的写日志的方法
- C#写日志两个简单方法
- C#2005 一个简单的写日志类
- c#写系统日志
- C#写日志类
- C#多线程写日志
- c#写系统日志
- C#多线程写日志
- C#写日志 方法
- C#写日志方法
- C# 写日志文件
- C# Log4 写日志
- c#写日志
- C#多线程写日志
- C#写日志
- C# 写系统日志
- C# 写日志
- Android 强行夺取EditText系统键盘输入改为自定义安全键盘输入
- 关系型数据库理论
- maven引jar包方法
- RecyclerView嵌套RecyclerView
- 在sublime中安装sass编译插件
- C#简单写日志
- javaRunTime
- MongoDB的基本操作命令
- 会员导入存储过程
- 技术人员如何创业《一》—— 产品及想法
- [LeetCode] 135. candy
- Android 混淆提示 java.io.FileNotFoundException: ...\proguard-rules\release\aapt_rules.txt (系统找不到指定的路径)
- vue.js的学习之路
- NHibernate从入门到精通系列(1)——NHibernate概括