C#简单记录日志
public void WriteLog(string msg)
{
string filePath = AppDomain.CurrentDomain.BaseDirectory + "Log";
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
string logPath = AppDomain.CurrentDomain.BaseDirectory + "Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
try
{
using (StreamWriter sw = File.AppendText(logPath))
{
//index:0为本身的方法;1为调用方法;2为其上上层,依次类推
MethodBase mb = new StackTrace(true).GetFrame(1).GetMethod();
sw .WriteLine("模块名:" + mb.Module);
if (mb.ReflectedType != null)
{
//完整类名,包括命名空间
sw .WriteLine("完整类名:" + mb.ReflectedType.FullName);
sw .WriteLine("方法名:" + mb.Name);
}
sw.WriteLine("消息:" + msg);
sw.WriteLine("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
sw.WriteLine("**************************************************");
sw.WriteLine();
sw.Flush();
sw.Close();
sw.Dispose();
}
}
catch (IOException e)
{
using (StreamWriter sw = File.AppendText(logPath))
{
sw.WriteLine("异常:" + e.Message);
sw.WriteLine("时间:" + DateTime.Now.ToString("yyy-MM-dd HH:mm:ss"));
sw.WriteLine("**************************************************");
sw.WriteLine();
sw.Flush();
sw.Close();
sw.Dispose();
}
}
}