using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Reflection.Metadata; using System.Text; namespace Utility.Tools { //private readonly ApiUrlConfig _config; //接口交互路径 public static class LogFile { /// 写LOG到本地文件方法,message="存入信息",path="存储路径" public static void SaveLogToFile(string message, string path = "./log/defaultlog.txt") { FileInfo fi = null; StreamWriter logWriter = null; try { int fileLength = 1024 * 1024 * 5;//5MB fi = new FileInfo(path); if (!fi.Directory.Exists) { fi.Directory.Create(); } if (fi.Exists && fi.Length > fileLength) { string newpath = path.Insert(path.LastIndexOf('.'), "_" + DateTime.Now.ToString("HHmmss")); File.Move(path, newpath); } logWriter = new StreamWriter(path, true); logWriter.WriteLine(DateTime.Now.ToString() + ">>>" + message); logWriter.WriteLine("----->."); DeleteLog(); //开启则为每次增加日志时进行删除大于1月的 } catch (Exception ex) { //throw ex; } finally { fi = null; if (logWriter != null) { logWriter.Close(); logWriter.Dispose(); } } } //删除指定日期文件,保留7天 public static void DeleteLogs(string Path, int days = 7) { //日志保留时长 单位:天 if (days<7) { days = 7; } try { if (!Directory.Exists(Path)) { return; } var now = DateTime.Now; foreach (var f in Directory.GetFileSystemEntries(Path).Where(f => File.Exists(f))) { var t = File.GetCreationTime(f); var elapsedTicks = now.Ticks - t.Ticks; var elaspsedSpan = new TimeSpan(elapsedTicks); if (elaspsedSpan.TotalDays > days) { File.Delete(f); } } } catch (Exception ex) { } } public static void DeleteLog() { UtilityUrlConfig _config = new UtilityUrlConfig(); string[] files = null; try { files = Directory.GetFiles(_config.Get130log); } catch { } finally { try { files = Directory.GetFiles(_config.Get131log); } catch (Exception ex) { throw new Exception(ex.Message); } } foreach (string file in files) { FileInfo fi = new FileInfo(file); if (fi.LastWriteTime < DateTime.Now.AddMonths(-1)) { fi.Delete(); } } } } }