日志帮助类(可自定义保存文件时长)
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading.Tasks;
namespace LogHelp
{
public class LogHelper
{
//创建文件锁
private readonly static object fileLock = new object();
private static string LogPath = AppDomain.CurrentDomain.BaseDirectory + "EmrInterface\\";
public static Dictionary<string, string> Paths = new Dictionary<string, string>()
{
["0"] = LogPath+ "GetOrderInfo\\",
["1"]= LogPath+ "StatusUpdate\\",
["2"] = LogPath+ "ReportBack\\",
["3"]= LogPath+ "CA\\",
["4"] =LogPath+ "DangerValue\\",
["5"]= LogPath+ "HISPushOrderInfo\\",
["6"] = LogPath + "HISPushAppointmentMessage\\",
["7"]= LogPath+ "360View",
};
/// <summary>
/// 清理多余的日志文件
/// </summary>
/// <param name="path"></param>
/// <param name="Year"></param>
/// <param name="Month"></param>
public static void DelectFileByTime(string path, string Year, string Month)
{
if (Directory.Exists(path))
{
DirectoryInfo Ydir = new DirectoryInfo(path);
DirectoryInfo[] Yfiles = Ydir.GetDirectories();
foreach (DirectoryInfo Yitem in Yfiles)
{
if (!string.IsNullOrEmpty(Year))
{
if (Yitem.Name == Year)
{
DelectFileByTime(Yitem.FullName, "", Month);
if (Month == "12")
{
Yitem.Delete(true);
}
}
else
{
try
{
if (Convert.ToInt32(Yitem.Name) < Convert.ToInt32(Year))
{
Yitem.Delete(true);
}
}
catch (Exception)
{
}
}
}
else if (!string.IsNullOrEmpty(Month))
{
if (Convert.ToInt32(Yitem.Name) <= Convert.ToInt32(Month))
{
Yitem.Delete(true);
}
}
}
}
}
/// <summary>
/// 添加日志
/// </summary>
/// <param name="strMessage">t添加的内容</param>
public static void AddLog(string LogPath, string strMessage)
{
try
{
DateTime dt = DateTime.Now;
//删除超过保存时长的文件
int savetime = 3;
//规定一个时间进行清理单位小时
int deleteTime = 15;
int Year = dt.Year;
int Month = dt.Month;
int time = dt.Hour;
int NewYear = Year;
int NewMonth = Month - savetime;
if (NewMonth <= 0)
{
NewYear = Year - 1;
NewMonth = 12 + NewMonth;
}
// string LogPath = AppDomain.CurrentDomain.BaseDirectory + "EmrInterface\\";
string path = LogPath + "\\" + dt.Year + "\\" + dt.Month + "\\";
if (deleteTime == time)
{
Task task = Task.Run(() =>
{
//清理不必要的日志文件
DelectFileByTime(LogPath, NewYear.ToString(), NewMonth.ToString());
});
}
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
string fileFullPath = path + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
StringBuilder str = new StringBuilder();
str.Append(DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss LEN=" + strMessage.Length.ToString() + "]") + strMessage + "\r\n");
//使用文件同步锁
lock (fileLock)
{
StreamWriter sw;
if (!File.Exists(fileFullPath))
{
sw = File.CreateText(fileFullPath);
}
else
{
sw = File.AppendText(fileFullPath);
}
sw.WriteLine(str.ToString());
sw.Close();
}
}
catch (Exception )
{
}
}
}
}

浙公网安备 33010602011771号