C#日志写入

时间:2021-12-07 17:41:50
public class Logs
{
/// <summary>
/// 写日志,指定日志文件
/// </summary>
/// <param name="File"></param>
/// <param name="Msg"></param>
public static void Info(string Msg)
{
try
{
string fileName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log\\Info\\info-" + DateTime.Now.ToString("yyyyMMdd") + ".lg");
string path = Path.GetDirectoryName(fileName);
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
System.IO.File.CreateText(fileName).Dispose();
}
else if (!System.IO.File.Exists(fileName))
{
System.IO.File.CreateText(fileName).Dispose();
}
using (TextWriter writer2 = System.IO.File.AppendText(fileName))
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
sb.AppendLine("消息记录时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
sb.AppendLine(Msg);
sb.AppendLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
sb.AppendLine("");
writer2.WriteLine(sb.ToString());
}
}
catch (Exception ex)
{ }
} public static void Error(string Title, Exception exception)
{
try
{
string fileName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log\\Error\\err-" + DateTime.Now.ToString("yyyyMMdd") + ".lg");
string path = Path.GetDirectoryName(fileName);
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
System.IO.File.CreateText(fileName).Dispose();
}
else if (!System.IO.File.Exists(fileName))
{
System.IO.File.CreateText(fileName).Dispose();
}
using (TextWriter writer2 = System.IO.File.AppendText(fileName))
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
sb.AppendLine("程序发生异常:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
sb.AppendLine("异常标题:" + Title);
GetExceptionMsg(exception, sb, "");
sb.AppendLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
sb.AppendLine("");
writer2.WriteLine(sb.ToString());
}
}
catch (Exception ex)
{ }
} static void GetExceptionMsg(Exception ex, StringBuilder sb, string Prefix = "")
{
sb.AppendLine(Prefix + "【异常类型】:" + ex.GetType().Name);
sb.AppendLine(Prefix + "【异常信息】:" + ex.Message);
sb.AppendLine(Prefix + "【堆栈调用】:" + ex.StackTrace);
sb.AppendLine(Prefix + "【异常方法】:" + ex.TargetSite); if (ex.InnerException != null)
GetExceptionMsg(ex.InnerException, sb, Prefix + "\t");
}
}