C#  Web应用中写错误日志

C#  Web应用中写错误日志 

#region 写日志
//读写锁,当资源处于写入模式时,其他线程写入需要等待本次写入结束之后才能继续写入
private readonly static ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
//当前网站服务器目录
private readonly static string mapPath = HttpContext.Current.Server.MapPath("~/");
/// <summary>
/// 写错误日志
/// </summary>
/// <param name="content"></param>
/// <param name="ex"></param>
public static void WriteErrorLog(string content,Exception ex)
{
    //web.config文件配置错误日志开关
    if (WebConfigurationManager.AppSettings["WeiXinChatLog"] == "开启")
    {
        try
        {
            //设置读写锁为写入模式独占资源,其他写入请求需要等待本次写入结束之后才能继续写入
            // 因进入与退出写入模式应在同一个try finally语句块内,所以在请求进入写入模式之前不能触发异常,否则释放次数大于请求次数将会触发异常
            LogWriteLock.EnterWriteLock();
            //错误日志存放文件夹
            string folder = string.Format(mapPath + @"Image\\{0}\\{1}", DateTime.Now.ToString("yyyy"), DateTime.Now.ToString("MM"));
            //判断文件夹是否存在
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            //File.WriteAllText(string.Format("{0}\\{1}.txt", folder, DateTime.Now.ToString("yyyyMMdd")), "测试信息向文件中覆盖写入信息", Encoding.UTF8);

            //在将文本写入文件前,处理文本行
            //StreamWriter第二个参数为false覆盖现有文件,为true则把文本追加到文件末尾
            using (StreamWriter file = new StreamWriter(string.Format("{0}\\{1}.txt", folder, DateTime.Now.ToString("dd")+"_err"), true))
            {
                file.WriteLine("【抛出时间】:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                file.WriteLine("【抛出信息】:"+content);
                file.WriteLine("【异常类型】:" + ex.GetType().Name); 
                file.WriteLine("【异常信息】:" + ex.Message);
                file.WriteLine("【堆栈调用】:" + ex.StackTrace);
                file.WriteLine("---------------------------------");
                file.WriteLine();//换行
                file.Close();
            }
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            //退出写入模式,释放资源占用 注意:一次请求对应一次释放

            LogWriteLock.ExitWriteLock();
        }
    }
}
#endregion

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值