VS编程,C# 后台存储操作日志的一种方法

有时为了记录逻辑执行的情况或者是响应前台的操作情况,需要记录相关的日志信息。

这里提供了一种记录日志的方法,txt格式。

原作者的文章

 1、右击程序集,建立一个日志类(命名为:WriteLog)

2、在类中加入如下代码

  • 将类定义为public属性
  public class WriteLoging
    {
        private static readonly object obj = new object();


        /// <summary>
        /// 操作日志
        /// </summary>
        /// <param name="s">日志能容</param>
        public  void WriteLog(string title, string content)
        {
            WriteLogs(title, content, "操作日志");
        }


        /// <summary>
        /// 错误日志
        /// </summary>
        /// <param name="s">日志内容</param>
        public  void WriteError(string title, string content)
        {
            WriteLogs(title, content, "错误日志");
        }



        public static void WriteLogs(string title, string content, string type)
        {
            lock (obj)
            {
                string path = AppDomain.CurrentDomain.BaseDirectory;
                if (!string.IsNullOrEmpty(path))
                {
                    path = AppDomain.CurrentDomain.BaseDirectory + "log";
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    path = path + "\\" + DateTime.Now.ToString("yyMM");
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    path = path + "\\" + DateTime.Now.ToString("dd") + ".txt";
                    if (!File.Exists(path))
                    {
                        FileStream fs = File.Create(path);
                        fs.Close();
                    }
                    if (File.Exists(path))
                    {
                        StreamWriter sw = new StreamWriter(path, true, System.Text.Encoding.Default);
                        sw.WriteLine(DateTime.Now + " " + title);
                        sw.WriteLine("日志类型:" + type);
                        sw.WriteLine("详情:" + content);
                        sw.WriteLine("----------------------------------------");
                        sw.Close();
                    }
                }
            }
        }
    }

 3、保存,并重新生成。

4、在所要记录日志的地方,实例一个公共的日志类,调用方法写日志

 

 5、在程序运行的目录下,会有一个Log的文件夹,内部按照日期分别创建文件夹,并以txt格式存储日志

 

 

猜你喜欢

转载自blog.csdn.net/qq_43307934/article/details/83110673
今日推荐