public class AppTestLog
{
/// <summary>
/// 此变量没有意义,只是为了lock使用
/// </summary>
private static object canUse = true;
/// <summary>
/// 是否需要记录日志
/// </summary>
private static bool NeedLog = true;
/// <summary>
/// 日志文件目录
/// </summary>
private const string logFoder = "LogInfo";
/// <summary>
/// 日志文件名
/// </summary>
/// <summary>
/// 日志文件名
/// </summary>
private static string logFileName
{
get { return DateTime.Now.ToString("yyyyMMdd") + "LogInfo.log"; }
}
/// <summary>
/// 日志文件全路径
/// </summary>
public static string LogFile
{
get
{
string file = LogFoder + "\\" + logFileName;
return file;
}
}
/// <summary>
/// 日志文件所在文件夹
/// 此方法2.0异常才支持
/// </summary>
public static string LogFoder
{
get
{
string s = "";
if (!string.IsNullOrEmpty(AppDomain.CurrentDomain.RelativeSearchPath))//说明是bs的
{
s = AppDomain.CurrentDomain.RelativeSearchPath + "\\" + logFoder;
s = s.Replace("\\\\", "\\");
}
else //不是BS的
{
s = AppDomain.CurrentDomain.BaseDirectory + "" + logFoder;
}
if (!Directory.Exists(s))
{
Directory.CreateDirectory(s);
}
return s;
}
}
/// <summary>
/// 写入日志
/// </summary>
/// <param name="logdate"></param>
/// <param name="loginfo"></param>
public static void AddLog(DateTime logdate, string loginfo)
{
if (NeedLog)
{
lock (canUse)
{
StreamWriter strWriter = new StreamWriter(LogFile, true);
strWriter.Write(logdate.ToString("yyyy-MM-dd HH:mm:ss"));
strWriter.Write(System.Environment.NewLine);
strWriter.Write(loginfo);
strWriter.Write(System.Environment.NewLine);
strWriter.Write(System.Environment.NewLine);
strWriter.Close();
}
}
}
}
使用方法: AppTestLog.AddLog(DateTime.Now, "开始……");
在bin目录的debug文件夹下按日期生成日志文件
最新推荐文章于 2021-05-01 15:00:01 发布