适用于不想使用log4net等第三方的Log工具的LogHelper。正规的还是要使用《C# 工具类LogHelper》的这种做法。
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FrameworkConsoleTest { public class BaseLogHelper { private static object _loglocker = new object();//锁对象 /// <summary> /// 写入日志文件 /// </summary> /// <param name="input">输入内容</param> public static void WriteLogFile(string input) { lock (_loglocker) { FileStream fs = null; StreamWriter sw = null; try { FileInfo fileInfo = null; fileInfo = CreateFileInfo("debug_"); fs = fileInfo.OpenWrite(); sw = new StreamWriter(fs); sw.BaseStream.Seek(0, SeekOrigin.End); sw.Write("Log Entry : "); sw.Write("{0}", DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss")); sw.Write(Environment.NewLine); sw.Write(input); sw.Write(Environment.NewLine); sw.Write("------------------------------------"); sw.Write(Environment.NewLine); } catch (Exception ex) { //throw ex; } finally { if (sw != null) { sw.Flush(); sw.Close(); } if (fs != null) { fs.Close(); } } } } protected static FileInfo CreateFileInfo(string ex) { FileInfo fileInfo = null; for (int i = 0; ; i++) { string fileName = GetMapPath("/Log/") + ex + DateTime.Now.ToString("yyyyMMdd") + "_" + i + ".log"; fileInfo = new FileInfo(fileName); if (!fileInfo.Directory.Exists) { fileInfo.Directory.Create(); } if (!fileInfo.Exists) { fileInfo.Create().Close(); } else if (fileInfo.Length > 2048 * 1000) { fileInfo = null; } if (fileInfo != null) return fileInfo; } } /// <summary> /// 获得当前绝对路径 /// </summary> /// <param name="strPath">指定的路径</param> /// <returns>绝对路径</returns> public static string GetMapPath(string strPath) { if (strPath.ToLower().StartsWith("http://")) { return strPath; } else //非web程序引用 { strPath = strPath.Replace("/", "\\"); if (strPath.StartsWith("\\")) { strPath = strPath.Substring(strPath.IndexOf(‘\\‘, 1)).TrimStart(‘\\‘); } return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath); } } } }