using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ImportDate
{
public class LogManager
{
///
/// 重要信息log
///
///
public static void MessageLog(params string[] logs)
{
try
{
object locker = new object();
lock (locker)
{
string path = Environment.CurrentDirectory + "//" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + ".log";
//判断文件是否存在,没有则创建。
if (!System.IO.File.Exists(path))
{
FileStream stream = System.IO.File.Create(path);
stream.Close();
stream.Dispose();
}
StreamWriter sw = new StreamWriter(path, true);
foreach (string log in logs)
{
sw.WriteLine(string.Format("[{0}] {1}", DateTime.Now.ToString(), log));
}
sw.Close();
//long size = 0;
//using (FileStream file = System.IO.File.OpenRead(path))
//{
// size = file.Length; //byte
//}
//文件大于1M,自动删除。
//if (size > (1024 * 3))
//{
// System.IO.File.Delete(path);
//}
}
}
catch (Exception ex)
{
ErrorLog(ex, "");
}
}
///
/// 将异常打印自定义的log文件里
///
///
///
public static void ErrorLog(Exception ex, string LogAddress)
{
if (LogAddress == "")
{
LogAddress = Environment.CurrentDirectory + "//" + "Error_" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + ".log";
}
StreamWriter sw = new StreamWriter(LogAddress, true);
sw.WriteLine("当前时间:" + DateTime.Now.ToString());
sw.WriteLine("异常信息:" + ex.Message);
sw.WriteLine("异常对象:" + ex.Source);
sw.WriteLine("调用堆栈:\n" + ex.StackTrace.Trim());
sw.WriteLine("触发方法:" + ex.TargetSite);
sw.WriteLine();
sw.Close();
}
}
}