zoukankan      html  css  js  c++  java
  • C#在服务器中记录日志的方法【简单】

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

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

    下面我们一起来看一下

     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 + "
    ");
                            }
                        }
                    }
                    catch (Exception eror)
                    {
                        string str = eror.ToString();
                        WriteLog(path, debugstr);
                    }
                }
            }
    

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

    就这样

  • 相关阅读:
    Redis线程模型理解
    策略模式
    Spring Cloud 5大组件介绍
    单例模式
    hotspot虚拟机的调试
    编译虚拟机jvm——openjdk的编译
    mybatis的搭建和注入spring的方式
    springMvc+hibernate的web application的构建
    关于本博客
    本博客已停更
  • 原文地址:https://www.cnblogs.com/SevenWang/p/14308030.html
Copyright © 2011-2022 走看看