class LogHelper
{
static Dictionary<string, object> objLook = new Dictionary<string, object>();
public static string m_Path = "LogMsg";//根目录的日志文件夹
public static void WriteServerLog(Exception ex, string Message = "")
{
string _Path = "ServerLog";//单个功能的日志文件夹
bool aa = objLook.ContainsKey(_Path);
if (!objLook.ContainsKey(_Path))
{
objLook.Add(_Path, new object());
}
lock (objLook[_Path])
{
string MonthNow = DateTime.Now.Month.ToString();
string DayNow = DateTime.Now.Day.ToString();
if (DateTime.Now.Month < 10)
{
MonthNow = "0" + MonthNow;
}
if (DateTime.Now.Day < 10)
{
DayNow = "0" + DayNow;
}
string LogAddress = AppDomain.CurrentDomain.BaseDirectory + m_Path + @"\" + _Path + @"\";
if (!System.IO.Directory.Exists(LogAddress))
{
Directory.CreateDirectory(LogAddress);
}
string LogAddress2 = LogAddress +
DateTime.Now.Year + '-' +
MonthNow + '-' +
DayNow + _Path + ".log";
//把异常信息输出到文件
StreamWriter fs = new StreamWriter(LogAddress2, true);
fs.WriteLine("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + ":" + Message);
// fs.WriteLine(Message);
if (ex != null)
{
fs.WriteLine("异常信息:" + ex.Message);
fs.WriteLine("异常对象:" + ex.Source);
fs.WriteLine("调用堆栈:\n" + ex.StackTrace.ToString());
fs.WriteLine("触发方法:" + ex.TargetSite);
}
fs.Close();
foreach (string str in Directory.GetFiles(LogAddress, "*.log", SearchOption.TopDirectoryOnly))
{
if (!str.Contains(DateTime.Now.Year + "-" + MonthNow + "-"))
{
File.Delete(str);
}
}
}
}
}
c#日志保存类,自动删除旧日志,只保存一个月内
最新推荐文章于 2024-08-05 22:01:02 发布