C#简单写日志

自己整理了一个简单写日志的类,方便以后再次用到。

说明:CS程序,程序启动目录下,自动创建Log目录,写日志。日志按天记录,每天的日志作为一个txt文件保存。

 /// <summary>
    /// 日志管理功能
    ///  //以天建立日志文件,
    /// </summary>
    public class LogManager
    {
        private static string LogDirectory = Application.StartupPath + @"\Log\";

        /// <summary>
        /// 保存的最多日志数量
        /// </summary>
        private static int MaxLogCount = 365;

        public static void Write(string msg)
        {
            try
            {
                DeleteLog();
                if (!System.IO.Directory.Exists(LogDirectory))
                {
                    System.IO.Directory.CreateDirectory(LogDirectory);
                }
                string name = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, ‘0‘) + DateTime.Now.Day.ToString().PadLeft(2, ‘0‘);
                string datapath = LogDirectory + name + ".txt";
                if (System.IO.File.Exists(datapath))//追加
                {
                    using (FileStream fs = new FileStream(datapath, FileMode.Append))
                    {
                        using (StreamWriter sw = new StreamWriter(fs))
                        {
                            //开始写入
                            sw.WriteLine("\n");
                            sw.WriteLine("当前时间:" + DateTime.Now.ToString());
                            sw.WriteLine("日志信息:" + msg);
                            //清空缓冲区
                            sw.Flush();
                            //关闭流
                            sw.Close();
                            fs.Close();
                        }
                    }
                }
                else//创建
                {
                    using (FileStream fs = new FileStream(datapath, FileMode.Create))
                    {
                        using (StreamWriter sw = new StreamWriter(fs))
                        {
                            //开始写入
                            sw.WriteLine("当前时间:" + DateTime.Now.ToString());
                            sw.WriteLine("日志信息:" + msg);
                            //清空缓冲区
                            sw.Flush();
                            //关闭流
                            sw.Close();
                            fs.Close();
                        }
                    }
                }
            }
            catch
            {

            }

        }

        public static void Write(Exception ex)
        {
            try
            {
                DeleteLog();
                if (!System.IO.Directory.Exists(LogDirectory))
                {
                    System.IO.Directory.CreateDirectory(LogDirectory);
                }
                string name = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, ‘0‘) + DateTime.Now.Day.ToString().PadLeft(2, ‘0‘);
                string datapath = LogDirectory + name + ".txt";//文件名格式为:20170606.txt
                if (System.IO.File.Exists(datapath))//追加
                {
                    using (FileStream fs = new FileStream(datapath, FileMode.Append))
                    {
                        using (StreamWriter sw = new StreamWriter(fs))
                        { //开始写入
                            sw.WriteLine("\n");
                            sw.WriteLine("当前时间:" + DateTime.Now.ToString());
                            sw.WriteLine("异常信息:" + ex.Message);
                            sw.WriteLine("异常对象:" + ex.Source);
                            sw.WriteLine("调用堆栈:" + ex.StackTrace);
                            sw.WriteLine("触发方法:" + ex.TargetSite);
                            //清空缓冲区
                            sw.Flush();
                            //关闭流
                            sw.Close();
                            fs.Close();
                        }
                    }
                }
                else//创建
                {
                    using (FileStream fs = new FileStream(datapath, FileMode.Create))
                    {
                        using (StreamWriter sw = new StreamWriter(fs))
                        {
                            //开始写入
                            sw.WriteLine("当前时间:" + DateTime.Now.ToString());
                            sw.WriteLine("异常信息:" + ex.Message);
                            sw.WriteLine("异常对象:" + ex.Source);
                            sw.WriteLine("调用堆栈:" + ex.StackTrace);
                            sw.WriteLine("触发方法:" + ex.TargetSite);
                            //清空缓冲区
                            sw.Flush();
                            //关闭流
                            sw.Close();
                            fs.Close();
                        }
                    }
                }
            }
            catch
            {

            }

        }

        /// <summary>
        /// 删除日志
        /// </summary>
        private static void DeleteLog()
        {
            DirectoryInfo dic = new DirectoryInfo(LogDirectory);

            //不必每天都删除日志,整10天删除
            if (!(DateTime.Now.Day % 10 == 0))
            {
                return;
            }

            if (dic.Exists)
            {
                var files = dic.GetFiles();
                if (files.Length < MaxLogCount)
                    return;

                List<int> names = new List<int>();
                for (int i = 0; i < files.Length; i++)
                {
                    string strname = Path.GetFileNameWithoutExtension(files[i].Name);
                    int name;
                    if (int.TryParse(strname, out name))
                    {
                        names.Add(name);
                    }
                }

                names.Sort();//升序
                //names.Reverse();//降序

                for (int i = 0; i < names.Count - MaxLogCount; i++)
                {
                    string path = System.IO.Path.Combine(LogDirectory, names[i].ToString() + ".txt");
                    File.Delete(path);
                }

            }
        }

    }

  

原文地址:https://www.cnblogs.com/zwcoding/p/9251273.html

时间: 2024-07-30 17:40:58

C#简单写日志的相关文章

轻轻松松教你写日志-超级简单

最近在做一个项目,涉及到很多的服务,一步步调试相当麻烦,要在自己电脑上发布很多服务,又要全部开启.很费时间,出现问题,怎么解决最快呢?直接写日志,一步定位哪里出了错. Log4Net库是一个帮助程序员将日志信息输出到各种目标(控制台.文件 数据库等)的工具. Log4Net,相信哪个程序员都用过,但是可能是人家配置好了自己拿过来直接用,所以让自己写还是有点困难,听起来很高大上的样子,其实真的很简单.以前听别人讲,迷迷糊糊,知道那么回事,就是个写日志的.但是真正会用还是在项目中自己真正的实践. 下

简单的分级别写日志程序

/************************************************************************/  /*   * 文件名称:write_log.cpp   * 摘    要:此文件实现了普通WINDOWS程序中的日志功能   *           主要有以下特点:   *           1. 根据日期创建日志文件目录,每天的日志分别存放在不同的日志目录中:   *           2. 日志内容分三种类型,根据不同需要,写不同的日志

一个不需要Log4Net的写日志的简单方法

有些项目写日志时会选择大名鼎鼎的Log4Net.而在我们使用它时,总会出现一些诸如版本不匹配而造成的写日志失败的情况,还要改web.config,还要改AssemblyInfo.而且,它的失败,并不是以日志的形式展现,而是“无反应”,你无法知道是哪里出了问题,最终的效果就是“没有输出日志且不知道为什么,需要根据百度和经验判断”.索性放弃.我只是要输出文本日志而已,杀鸡不要用牛刀了. 以下是一个简单实用的日志类,无需配置. public class LogHelper { public stati

C# 简单的往txt中写日志,调试时很有用

原文 http://blog.csdn.net/hejialin666/article/details/6106648 有些程序在调试时很难抓住断点(如服务程序),有些程序需要循环无数次,要看每一次或某一次的结果,等等吧! 那就来个简单的写日志程序吧,txt文件生成在debug目录里 using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Windows.Fo

C# 超高速高性能写日志 代码开源

1.需求 需求很简单,就是在C#开发中高速写日志.比如在高并发,高流量的地方需要写日志.我们知道程序在操作磁盘时是比较耗时的,所以我们把日志写到磁盘上会有一定的时间耗在上面,这些并不是我们想看到的. 2.解决方案 2.1.简单原理说明 使用列队先缓存到内存,然后我们一直有个线程再从列队中写到磁盘上,这样就可以高速高性能的写日志了.因为速度慢的地方我们分离出来了,也就是说程序在把日志扔给列队后,程序的日志部分就算完成了,后面操作磁盘耗时的部分程序是不需要关心的,由另一个线程操作. 俗话说,鱼和熊掌

利用TraceSource写日志

利用TraceSource写日志 从微软推出第一个版本的.NET Framework的时候,就在“System.Diagnostics”命名空间中提供了Debug和Trace两个类帮助我们完成针对调试和跟踪信息的日志记录.在.NET Framework 2.0中,微软引入了TraceSource并对跟踪日志系统进行了优化,优化后的跟踪日志系统在.NET Core中又经过了相应的简化..NET Core的日志模型借助TraceSourceLoggerProvider实现对TraceSource的整

C++ 简单的日志类

/* 简单的日志记录类. (日志而已,何必那么复杂!!!) W.J.Chang 2013.12.13 说明:(EasyLog.h) 1, 简单的单件实现(自动垃圾回收) 2, 使用方法:EasyLog::Inst()->Log("Run..."); 3, 日志记录结果:Run... [2013.12.13 16:38:42 Friday] */ #pragma once #ifndef EASY_LOG_H_8080 #define EASY_LOG_H_8080 #includ

简单的日志管理代码

自己写的记录日志,定期删除日志的方法. 方法比较简单,记录一下吧. /// <summary> /// 写日志 /// </summary> /// <param name="strMsg">内容</param> /// <param name="strPath">路径(相对hycom下的文件夹路径)</param> /// <param name="fileName"

NodeJS写日志_Log4js使用详解

今天和大家分享一下NodeJS中写日志的一个常用第三方包:Log4js. 跟随主流Blog特色,先简单介绍下Log4js的基本信息.介绍Log4js之前,需要先说一下Log4***,Log4***是由Apache提供的多平台下多语言下日志书写扩展包,目的很简单就是使日志书写更加方便简洁,同时对不同的业务日志能够进行灵活的分文件记录,同时也包含着详细的等级配置,为之后分级输出,检索,及程序自动解析提供更加便捷的支持(一家之言,非官方描述,领会精神).Log4***有很多语言的实现,比如Log4cp