using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Web; namespace BLWWS_BLL { /// /// 日志辅助类 /// public static class LogHelper { public static string ExePath = HttpContext.Current.Request.PhysicalApplicationPath; /// /// 日志写入到批定的文件路径下 /// /// public static void WriteLog(string msg, string path = "") { if (string.IsNullOrEmpty(path)) { path = ExePath; } path = path + "\\logs\\" + DateTime.Now.ToString("yyyyMMdd") + ".log"; msg = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":\t" + HttpContext.Current.Request.UserHostAddress + ":" + msg + Environment.NewLine; WriteLog(path, msg, true); } public static void WriteLogNew(string msg, string path = "") { if (string.IsNullOrEmpty(path)) { path = ExePath; } path = path + "\\logs\\" + DateTime.Now.ToString("yyyyMMdd") + ".log"; msg = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":\t" + msg + Environment.NewLine; WriteLog(path, msg, true); } /// /// 把数据写入指定的文件里 /// /// 文件路径(包括文件名称) /// 写入内容 /// 是否追加 public static void WriteLog(string path, string msg, bool append) { string folder = Path.GetDirectoryName(path); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } StreamWriter sw = null; try { sw = new StreamWriter(path, append, Encoding.Unicode); sw.WriteLine(msg); } catch (Exception) { } finally { if (sw != null) { sw.Close(); } } } /// /// 把数据写入指定的文件里 /// /// /// public static void WriteLog(string path, byte[] msg) { string folder = Path.GetDirectoryName(path); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } FileStream fs = null; try { fs = new FileStream(path, FileMode.Append, FileAccess.Write); fs.Write(msg, 0, msg.Length); } catch (Exception) { } finally { if (fs != null) { fs.Close(); } } } /// /// 读取文件内容 /// /// /// public static string ReadLog(string path) { if (File.Exists(path)) { StreamReader sr = null; try { sr = new StreamReader(path); return sr.ReadToEnd(); } catch (Exception) { } finally { if (sr != null) { sr.Close(); } } } return ""; } } }