1、首先写日志帮助类
public class TextLogHelper
{
/// <summary>
/// 打印文本日志
/// </summary>
/// <param name="url"></param>
/// <param name="ex"></param>
/// <param name="param"></param>
public static void PrintLog(string url, Exception ex, string param = "")
{
string folderNew = Directory.GetCurrentDirectory() + "/OperateLog/" + DateTime.Now.ToString("yyyy-MM-dd");
string pathFileNew = folderNew + "/" + DateTime.Now.Hour + ".log";//记事本文件名
if (!FileHelper.FolderExists(folderNew))
FileHelper.CreateFolder(folderNew);
StringBuilder sb = new StringBuilder();
sb.AppendLine($"--------------------------------------{DateTime.Now}--------------------------------------");
sb.Append(string.Format("请求参数--{0}\r\n", param));
sb.Append(string.Format("请求时间--{0}\r\n", DateTime.Now));
sb.Append(string.Format("请求地址--{0}\r\n", url));
sb.Append(string.Format("异常信息--{0}\r\n", ex == null ? "" : ex.Message));
sb.Append(string.Format("堆栈信息--{0}\r\n", ex == null ? "" : ex.StackTrace));
sb.AppendLine($"--------------------------------------{DateTime.Now}--------------------------------------");
FileHelper.WriteFile(pathFileNew, sb.ToString());
}
}
public class FileHelper
{
public static bool WriteFile(string filePath, string fileContent)
{
return WriteFile(filePath, fileContent, true);
}
public static bool WriteFile(string filePath, string fileContent, bool append)
{
try
{
StreamWriter sw = new StreamWriter(filePath, append);
sw.WriteLine(fileContent);
sw.Close();
return true;
}
catch
{
return false;
}
}
public static string ReadFile(string filePath)
{
try
{
StreamReader sr = new StreamReader(filePath);
string fileContent = sr.ReadToEnd();
sr.Close();
return fileContent;
}
catch
{
return string.Empty;
}
}
public static bool FolderExists(string folder)
{
return Directory.Exists(folder);
}
public static DirectoryInfo CreateFolder(string folder)
{
return Directory.CreateDirectory(folder);
}
public static bool FileExists(string filePath)
{
return File.Exists(filePath);
}
}
2、测试
[HttpPost]
public IActionResult TestTextLog(TextLogModel model)
{
try
{
Student? stu = null;
var name = stu.Name;
return ToSuccess(name);
}
catch (Exception ex)
{
//调用日志方法
TextLogHelper.PrintLog($"api/{GetType().Name}/TestTextLog", ex, JsonConvert.SerializeObject(model));
throw;
}
}
3、效果