2025-03-28 09:49:56 +08:00

79 lines
2.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ImportDate
{
public class LogManager
{
/// <summary>
/// 重要信息log
/// </summary>
/// <param name="logs"></param>
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, "");
}
}
/// <summary>
/// 将异常打印自定义的log文件里
/// </summary>
/// <param name="ex"></param>
/// <param name="LogAddress"></param>
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();
}
}
}