using System;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
/// <summary>
/// 本地日志辅助类
/// </summary>
public class LocalLogHelper
{
/// <summary>
/// 写日志方法
/// </summary>
/// <param name="logstring">The logstring.</param>
public static void WriteLog(string logstring)
{
Type type = typeof(LocalLogHelper);
Monitor.Enter(type);
try
{
string str = Path.Combine(Application.StartupPath, "Log");
if (!Directory.Exists(str))
{
Directory.CreateDirectory(str);
}
string fullName = Assembly.GetCallingAssembly().FullName;
//string str1 = Path.Combine(str, string.Concat(fullName.Substring(0, fullName.IndexOf(",", StringComparison.Ordinal)), ".txt"));
string str1 = Path.Combine(str, string.Concat(Application.ProductName, ".txt"));
FileInfo logFile = new FileInfo(str1);
if (File.Exists(str1) && logFile.Length > 2000000) //如果日志文件大于该值则另存为.bak文件
{
File.Copy(str1, string.Concat(str1 + DateTime.Now.ToString("yyyyMMdd"), ".bak"), true);
File.Delete(str1);
}
StreamWriter streamWriter = null;
try
{
streamWriter = new StreamWriter(str1, true, Encoding.GetEncoding("gb2312"));
DateTime now = DateTime.Now;
streamWriter.WriteLine(string.Concat("时间:", now.ToString("G")));
//string fullName = Assembly.GetCallingAssembly().FullName;
int hashCode = Assembly.GetCallingAssembly().GetHashCode();
streamWriter.WriteLine(string.Concat("调用模块:", fullName, hashCode.ToString()));
streamWriter.WriteLine(string.Concat("信息:", logstring));
streamWriter.WriteLine();
}
finally
{
streamWriter?.Close();
}
}
finally
{
Monitor.Exit(type);
}
}
}