C# 后台添加Log信息

我们在做项目的时候,经常会使用到Log日志,今天分享一下如何在后台添加Log信息

 

创建一个写Log的方法:

 1 public void WriteLog(string Action)
 2     {
 3         try
 4         {
 5             string strLogPath = System.Configuration.ConfigurationManager.AppSettings["LogPath"].ToString();
 6             string strLogName = System.DateTime.Now.ToString("yyyy/MM/dd").Replace("/", "-");
 7             string strIP = Request.UserHostAddress + ":" + Request.Url.Port;//訪問者的Ip和端口
 8             if (!strLogPath.EndsWith("\\"))
 9                 strLogPath += "\\";
10             strLogPath += "Log\\";
11             //判斷是否有這樣的路徑并創建
12             if (System.IO.Directory.Exists(strLogPath) == false)
13             {
14                 System.IO.Directory.CreateDirectory(strLogPath);
15             }
16             strLogName = strLogPath + strLogName + ".txt";
17             ////如果文件不存在,會自動創建
18             string strNote = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
19             strNote += ":" + strIP + ":\n" + Action + "\n\n";
20             System.IO.StreamWriter file = new System.IO.StreamWriter(strLogName, true);
21             file.WriteLine(strNote);
22             file.Close();
23             file.Dispose();
24         }
25         catch //(Exception ex)
26         {
27 
28         }
29     }

 

调用事件:

 1 protected void ibtnQuery_Click(object sender, EventArgs e)
 2     {
 3         try
 4         {           
 5             Query();
 6         }
 7         catch (Exception ex) 
 8         { 
 9             WriteLog(ex.Message); 
10         }
11     }    

 

效果展示:

 

 

如果您看了本篇博客,觉得对您有所收获,请点击右下角的 [推荐]

如果您想转载本博客,请注明出处

如果您对本文有意见或者建议,欢迎留言

感谢您的阅读,请关注我的后续博客

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值