C#在服务器中记录日志的方法【简单】

今天我们来写一个记录日志的方法

日志是我们在开发环境中必不可少的记录Bug点的东西。那么用C#中的原生File应该怎么去写呢?

下面我们一起来看一下

 

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
private static readonly object writeFile = new object();
       public static void WriteLog(string debugstr)
       {
           WriteLog(HttpContext.Current.Server.MapPath("~/Log"), debugstr);
       }
       private static void WriteLog(string path, string debugstr)
       {
           lock (writeFile)
           {
               try
               {
                   string filename = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                   //日志目录
                   if (!Directory.Exists(path))
                   {
                       Directory.CreateDirectory(path);
                   }
                   using (FileStream fs = new FileStream(path + "/" + filename, FileMode.Append,FileAccess.Write))
                   {
                       using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
                       {
                           sw.WriteLine(DateTime.Now.ToString() + "     " + debugstr + "\r\n");
                       }
                   }
               }
               catch (Exception eror)
               {
                   string str = eror.ToString();
                   WriteLog(path, debugstr);
               }
           }
       }

 内容比较简单,提供了一个默认的重载。直接调用写内容就可以了。

就这样

posted @   王月半子  阅读(397)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示