C#简单写日志
标签:文件 targe write names sts create startup out 写入
自己整理了一个简单写日志的类,方便以后再次用到。
说明:CS程序,程序启动目录下,自动创建Log目录,写日志。日志按天记录,每天的日志作为一个txt文件保存。
///
/// 日志管理功能
/// //以天建立日志文件,
///
public class LogManager
{
private static string LogDirectory = Application.StartupPath + @"\Log\";
///
/// 保存的最多日志数量
///
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
{
}
}
///
/// 删除日志
///
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 names = new List();
for (int i = 0; i
C#简单写日志
标签:文件 targe write names sts create startup out 写入
原文地址:https://www.cnblogs.com/zwcoding/p/9251273.html
文章来自:
搜素材网的
编程语言模块,转载请注明文章出处。
文章标题:
C#简单写日志
文章链接:http://soscw.com/index.php/essay/70549.html
评论