加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

c#自定义日志记录

发布时间:2020-12-16 08:55:31 所属栏目:asp.Net 来源:网络整理
导读:前言:自定义写入日志,需要注意多线程下文件读取写入时异常问题处理:下面列举了2种优化方案: 废话不多说,直接上代码: ? 很简单:将类复制到项目中,最后在配置文件上配置一下:logUrl即可。 默认保存在:项目/temp/log ?自定义日志类1: /// summary //

前言:自定义写入日志,需要注意多线程下文件读取写入时异常问题处理:下面列举了2种优化方案:

废话不多说,直接上代码:

?

很简单:将类复制到项目中,最后在配置文件上配置一下:logUrl即可。 默认保存在:项目/temp/log

?自定义日志类1:

/// <summary>
    /// 日志类
    </summary>
    <remarks>Creator: v-lxh  CreateTime: 2016/7/26 11:18:09</remarks>
    <Description></Description>
    public class Log
    {
        <summary>
         写入日志.
        </summary>
        <param name="strList">The STR list.</param>
        </remarks>
        <Description></Description>
        static void WriteLog(params object[] strList)
        {
            //判断是否开启日志模式
            if (!LogModel) return;
            if (strList.Count() == 0) return;
            日志文件路径
            string strDicPath = ""try
            {
                strDicPath = HttpContext.Current.Server.MapPath("~/temp/log/");
                if (strDicPath == null || strDicPath == )
                {
                    strDicPath = System.Configuration.ConfigurationManager.AppSettings[logUrl"] + /temp/log/;
                }
            }
            catch (Exception e)
            {
                strDicPath = System.Configuration.ConfigurationManager.AppSettings[;
            }
            string strPath = strDicPath + string.Format({0:yyyy年-MM月-dd日}",DateTime.Now) + 日志记录.txtif (!Directory.Exists(strDicPath))
            {
                Directory.CreateDirectory(strDicPath);
            }
            File.Exists(strPath))
            {
                using (FileStream fs = File.Create(strPath)) { }
            }
            string str = File.ReadAllText(strPath);
            StringBuilder sb = new StringBuilder();
            foreach (var item in strList)
            {
                sb.Append(rn" + DateTime.Now.ToString() + -----" + item + );
            }
            File.WriteAllText(strPath,sb.ToString() + rn-----z-----rn" + str);
        }

    }

?

??初稿1--优化1-使用Lock锁定资源:

?

   Creator: lixh  CreateTime: 2017/3/23 11:18:09 Log
    {
        日期文件夹路径
        ;

        静态方法todo:在处理话类型之前自动调用,去检查日志文件夹是否存在
        static Log()
        {
            todo:通过当前http请求上下文获取的服务器相对路径下的物理路径--非静态资源--占用资源
            string strDicPath = System.Web.HttpContext.Current.Server.MapPath("~/temp/log/");

            静态类型--获取应用所在的物理路径--节省资源
            //strDicPath = System.Web.HttpRuntime.AppDomainAppPath + "templogs";
       //winform等非web程序可使用以下方法:
       strDicPath = System.Threading.Thread.GetDomain().BaseDirectory.Replace("binDebug","") + "templogs";
创建文件夹 Directory.Exists(strDicPath)) { Directory.CreateDirectory(strDicPath); } } <remarks> string strPath = ""; 文件路径 { strPath = strDicPath + (Exception e) { strDicPath = C:templog; strPath = strDicPath + ; } todo:自动创建文件(但不能创建文件夹),并设置文件内容追加模式,使用using会自动释放FileSteam资源 using (FileStream stream = FileStream(strPath,FileMode.Append)) { lock (stream) 锁定资源,一次只允许一个线程写入 { StreamWriter write = StreamWriter(stream); string content = ; var str strList) { content += str; } content += ; write.WriteLine(content); 关闭并销毁流写入文件 write.Close(); write.Dispose(); } } } <remarks></remarks> void WriteLog(Action DefFunc,Func<string> ErrorFunc = null) { { DefFunc(); } (Exception ex) { ; todo:自动创建文件(但不能创建文件夹),并设置文件内容追加模式,使用using会自动释放FileSteam资源 lock (stream) { StreamWriter write = StreamWriter(stream); ex.Message; content += ex.StackTrace; content += ; write.WriteLine(content); write.Close(); write.Dispose(); } } } } }

?

//初稿2-优化-使用微软提供的读写锁:

读写锁,当资源处于写入模式时,其他线程写入需要等待本次写入结束之后才能继续写入
        private static ReaderWriterLockSlim LogWriteLock =  ReaderWriterLockSlim();
        
            {
                todo:自动创建文件(但不能创建文件夹),并设置文件内容追加模式,使用using会自动释放FileSteam资源
                LogWriteLock.EnterWriteLock();

                                    write.Close();
                    write.Dispose();
                }
            }
             (Exception)
            {

            }
            finally {
                LogWriteLock.ExitWriteLock();
            }
        }

?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读