using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CommHelper
{
public class ErrorFileLog
{
/// <summary>
/// 写日志信息
/// </summary>
/// <param name="asWriteInfo"></param>
public static void WriteInfo(string asWriteInfo)
{
string sPath = AppConfig.GetString("LogPath") ;
if (sPath == null || sPath == "")
{
sPath = "C:\\Log";
}
sPath = sPath.TrimEnd('\\');
FileStream fs = null;
try
{
if (!Directory.Exists(sPath))
{
Directory.CreateDirectory(sPath);
}
string path = sPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".info";
if (!File.Exists(path))
{
using (fs = File.Create(path)) { }
}
using (fs = File.Open(path, System.IO.FileMode.Append))
{
Byte[] info =
new System.Text.UTF8Encoding(true).GetBytes(DateTime.Now.ToString() + " 记录:\r\n" + asWriteInfo + "\r\n");
fs.Write(info, 0, info.Length);
}
}
finally
{
if (fs != null)
{
fs.Close();
}
}
}
/// <summary>
/// 写入异常信息
/// </summary>
/// <param name="exception"></param>
/// <param name="error"></param>
public static void WriteError(Exception exception, string error)
{
string sPath = AppConfig.GetString("LogPath");
if (sPath == null || sPath == "")
{
sPath = "C:\\Log";
}
sPath = sPath.TrimEnd('\\');
if (!Directory.Exists(sPath))
{
Directory.CreateDirectory(sPath);
}
error = string.Format("{0} {1} \r\n", DateTime.Now, GetExceptionFullError(exception, error));
byte[] bytes = UTF8Encoding.UTF8.GetBytes(error);
int length = bytes.Length;
string logfile = Path.Combine(sPath ,DateTime.Now.ToString("yyyyMMdd") + ".log");
FileStream w = null;
if (!File.Exists(logfile))
{
using (w = File.Create(logfile)) { }
}
try
{
w = File.Open(logfile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
w.Position = w.Length;
w.Write(bytes, 0, length);
}
finally
{
if (w != null)
{
w.Close();
}
}
}
/// <summary>
/// 格式化异常信息
/// </summary>
/// <param name="exception"></param>
/// <param name="error"></param>
/// <returns></returns>
private static string GetExceptionFullError(Exception exception, string error)
{
if (error == null)
{
error = string.Empty;
}
if (exception != null)
{
if (error.Length > 0)
{
error += " ";// Environment.NewLine;
}
error += GetExceptionFullError(exception);
}
return error;
}
/// <summary>
/// 格式化异常信息
/// </summary>
/// <param name="exception"></param>
/// <returns></returns>
private static string GetExceptionFullError(Exception exception)
{
string builder = "";
while (exception != null)
{
builder += exception.Message;
builder += " ";
exception = exception.InnerException;
}
if (builder.Length > 0)
{
return builder.ToString();
}
else
{
return null;
}
}
}
}