调用:
Logger.Add(“出参:”+“测试测试测试”);
public class Logger
{
private static int FileSize = 1 * 1024 * 1024;
private static string logfile = AppDomain.CurrentDomain.BaseDirectory + "\\logs\\log{0}.txt";
private static object locker = new object();
private static bool IsStop = false;
private static System.Threading.Thread logTh;
private static Queue<string> LogQueues = new Queue<string>();
public Logger()
{
}
static void Run()
{
while (!IsStop)
{
lock (locker)
{
if (LogQueues.Count <= 0)
{
System.Threading.Thread.Sleep(1);
continue;
}
}
var msg = LogQueues.Dequeue();
Write(msg);
}
}
/// <summary>
/// 添加日志到日志队列
/// </summary>
/// <param name="msg"></param>
public static void Add(string msg)
{
if (logTh == null)
{
logTh = new System.Threading.Thread(Run);
logTh.Start();
}
lock (locker)
{
LogQueues.Enqueue(msg);
}
}
/// <summary>
/// 停止
/// </summary>
public static void Stop()
{
IsStop = true;
}
/// <summary>
/// 写log
/// </summary>
/// <param name="msg"></param>
static void Write(string msg)
{
string file = string.Format(logfile, DateTime.Now.ToString("yyyy-MM-dd"));
string dir = System.IO.Path.GetDirectoryName(file);
if (!System.IO.Directory.Exists(dir))
{
System.IO.Directory.CreateDirectory(dir);
}
if (System.IO.File.Exists(file))
{
System.IO.FileInfo info = new System.IO.FileInfo(file);
if (info != null && info.Length > FileSize)
{
string destFile = "";
int i = 1;
while (true)
{
destFile = file + ".bak_" + i + ".txt";
i++;
if (!System.IO.File.Exists(destFile))
{
break;
}
}
System.IO.File.Move(file, destFile);
}
}
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(file, true))
{
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "===============");
sw.WriteLine(msg);
sw.WriteLine("");
}
}
}
1748




被折叠的 条评论
为什么被折叠?



