c# 简单日志记录类 log
共享一下很久写的一个日志记录类
网上的日志记录DLL,复杂繁多,最典型的就是log4net
但是往往你又不需要这么高级的东东(唉!配置麻烦),干脆自己弄一个简单的日志记录工具类,还算凑合着用(主要是并发记录日志和多线程的问题).
喜欢的就拿去用吧! 以后有时间把它改成多线程的就完美了。
上代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | using System; namespace NatureSex.CommonTool.Log { /// <summary> /// 日志等级 /// </summary> public enum LoggerWarnLevel { /// <summary> /// 日常等级 /// </summary> Info = 1, /// <summary> /// 错误等级 /// </summary> Error = 2 } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 | using System; using System.Text; using System.IO; namespace NatureSex.CommonTool.Log { /// <summary> /// 作者:NatureSex 创建时间:2011-03-25 17:09:07 /// 名称:简单日志记录类 /// 默认使用配置文件APPSetting名称为FilePath节点值 /// 一个范围内写文件不会马上关闭流,需要手动调用Dispose方法释放,或者使用using实例化该类 /// </summary> public class SimpleLogger : IDisposable { private static string appSettingPath = System.Configuration.ConfigurationManager.AppSettings[ "FilePath" ]; private static string logPath = null ; /// <summary> /// 存放路径 /// </summary> public string LogPath { get { return logPath; } set { logPath = value; } } private static int logSize = 2048; /// <summary> /// 每个日志文件大小(kb) /// </summary> public static int LogSize { get { return logSize; } set { logSize = value; } } private static int maxCount = 5; /// <summary> /// 每天日志文件最大记录数量 /// </summary> public static int MaxCount { get { return maxCount; } set { maxCount = value; } } private static string logSuffix = "log" ; /// <summary> /// 日志文件后缀名 /// </summary> public static string LogSuffix { get { return logSuffix; } set { logSuffix = value; } } private static int lineCharCount = 60; /// <summary> /// 行字数,默认60 /// </summary> public static int LineCharCount { get { return lineCharCount; } set { lineCharCount = value; } } FileStream newfs = null ; FileInfo openfile = null ; StreamWriter sw = null ; static SimpleLogger() { } /// <summary> /// 使用配置文件AppSetting节点name为FilePath中value路径实例化 /// </summary> public SimpleLogger() { if ( string .IsNullOrEmpty(logPath) && appSettingPath != "" ) { if (logPath == null ) { logPath = appSettingPath + "/Log" ; CreateMatchFolder(logPath); } } } /// <summary> /// 使用自定义的路径实例化 /// </summary> /// <param name="logPathPrams"></param> public SimpleLogger( string logPathPrams) { if (!Path.HasExtension(logPathPrams)) { if (logPath == null ) { logPath = logPathPrams + "/Log" ; CreateMatchFolder(logPath); } } else { throw new Exception( "路径不能包含文件名称!" ); } } private static void CreateMatchFolder( string path) { if (!Directory.Exists(logPath)) { Directory.CreateDirectory(path); } } /// <summary> /// 写入日常日志信息 /// </summary> /// <param name="title">标题</param> /// <param name="info">内容</param> public bool WriteInfoLog( string title, string info) { return WriteFile(logPath, title, LoggerWarnLevel.Info, info); } /// <summary> /// 写入日常日志信息 /// </summary> /// <param name="title">标题</param> /// <param name="info">内容</param> /// <param name="autoNewLine">是否自动换行</param> /// <returns></returns> public bool WriteInfoLog( string title, string info, bool autoNewLine) { string [] newinfo = SplitString(info); return WriteFile(logPath, title, LoggerWarnLevel.Info, newinfo); } /// <summary> /// 写入错误日志信息 /// </summary> /// <param name="title">标题</param> /// <param name="info">内容</param> public bool WriteErrorLog( string title, Exception ex) { return WriteFile(logPath, title, LoggerWarnLevel.Error, ex.Message); } /// <summary> /// 写入错误日志信息 /// </summary> /// <param name="title">标题</param> /// <param name="info">内容</param> /// <param name="autoNewLine">是否自动换行</param> /// <returns></returns> public bool WriteErrorLog( string title, Exception ex, bool autoNewLine) { string [] newinfo = SplitString(ex.Message); return WriteFile(logPath, title, LoggerWarnLevel.Error, newinfo); } //lineCharCount个字换一行 private string [] SplitString( string info) { int charLen = info.Length; int line = ( int )Math.Ceiling((charLen / ( double )lineCharCount)); string [] splitArray = new string [line]; //行数 for ( int i = 0; i < line; i++) { if (charLen < lineCharCount) { splitArray[i] = info; } else if ((charLen - (i * lineCharCount)) < lineCharCount) { splitArray[i] = info.Substring(i * lineCharCount, charLen - (i * lineCharCount)); } else { splitArray[i] = info.Substring(i * lineCharCount, lineCharCount); } } return splitArray; } /// <summary> /// 写入日志 /// </summary> /// <param name="path"></param> /// <param name="title"></param> /// <param name="level"></param> /// <param name="info"></param> /// <returns></returns> private bool WriteFile( string path, string title, LoggerWarnLevel level, params string [] info) { string fileName = string .Format( "{0}.{1}" , DateTime.Now.ToString( "yyyy-MM-dd" ), logSuffix); string logFile = string .Format( "{0}/{1}" , path, fileName); if (!File.Exists(logFile)) { CreateNewLog(logFile); } if (openfile == null || sw == null ) { openfile = new FileInfo(logFile); long sizeKB = (openfile.Length / 1024); if (sizeKB > logSize) { logFile = FindCanWriteFileName(path, fileName); CreateNewLog(logFile); openfile = new FileInfo(logFile); } newfs = openfile.Open(FileMode.Append, FileAccess.Write, FileShare.ReadWrite); sw = new StreamWriter(newfs); } if (sw == null ) return false ; sw.WriteLine( "================{0}=================" , title); sw.WriteLine( "记录时间:{0} 等级:{1}" , DateTime.Now.ToString(), level == LoggerWarnLevel.Info ? "info" : "error" ); sw.WriteLine(); if (info != null ) { foreach ( string str in info) { sw.WriteLine(str); } } sw.WriteLine(); sw.Flush(); return true ; } /// <summary> /// 建立一个新日志文件 /// </summary> /// <param name="logFile"></param> private void CreateNewLog( string logFile) { if (!File.Exists(logFile)) { using (newfs = new FileStream(logFile, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite)) { sw = new StreamWriter(newfs, Encoding.UTF8); sw.WriteLine( "文件创建时间:{0}" , DateTime.Now.ToString()); sw.WriteLine( "文件最大记录大小:{0}KB(与实际可能会有出入)" , logSize); sw.WriteLine(sw.NewLine); newfs.Flush(); sw.Dispose(); sw = null ; } } } /// <summary> /// 寻找一个当天可写的文件,并且不大于设置的文件大小 /// </summary> /// <param name="path"></param> /// <param name="name"></param> /// <returns></returns> private string FindCanWriteFileName( string path, string name) { string newName = string .Empty; long sizeKB = 0; FileInfo tempFi = null ; for ( int i = 1; i <= MaxCount; i++) { newName = string .Format( "{0}/{2}-{1}" , path, name, i); if (!File.Exists(newName)) { break ; } else { tempFi = new FileInfo(newName); sizeKB = (tempFi.Length / 1024); if (sizeKB < logSize) { break ; } } } tempFi = null ; return newName; } #region Dispose private bool disposed = false ; /// <summary> /// 垃圾回收器执行函数 /// </summary> ~SimpleLogger() { //如果有就释放非托管 Dispose( false ); } /// <summary> /// 关闭并是否资源 /// </summary> public void Dispose() { //全部释放 Dispose( true ); GC.SuppressFinalize( this ); } /// <summary> /// 关闭并是否资源 /// </summary> public void Close() { Dispose(); } /// <summary> /// 关闭并是否资源 /// </summary> protected virtual void Dispose( bool disposing) { if (disposed) { return ; } // 清理托管资源 if (disposing) { if (sw != null ) { sw.Close(); sw.Dispose(); sw = null ; } if (newfs != null ) { newfs.Close(); newfs.Dispose(); newfs = null ; } if (openfile != null ) { openfile = null ; } } //非托管 disposed = true ; } #endregion } } |
如果觉得本文适合您且对您有帮助,请一定记得点推荐哟!
![]() |
作者:
JasNature 出处: http://NatureSex.cnblogs.com 本文版权归作者和博客园共有,欢迎转载,但必须保留此段声明,且在文章页面明显位置给出原文连接。 如果本文有什么不妥或者错误的地方,请您一定要在评论中指出,以免误人子弟!非常感谢您的不吝赐教! | ||
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述