当前位置:主页 > 查看内容

C#写log,自家用

发布时间:2021-06-15 00:00| 位朋友查看

简介:简单的文件读写来写log功能不多但能满足日常使用资源占用小上代码 示例程序百度云链接 链接https://pan.baidu.com/s/15bc2Q52Jwzysv6_xnWD41w 提取码afms 复制这段内容后打开百度网盘手机App操作更方便哦 using System ; using System . Collections . Concu……

简单的文件读写来写log,功能不多但能满足日常使用,资源占用小,上代码:
示例程序百度云链接:
链接:https://pan.baidu.com/s/15bc2Q52Jwzysv6_xnWD41w
提取码:afms
复制这段内容后打开百度网盘手机App,操作更方便哦

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;


/// <summary>
    /// 日志记录工具
    /// </summary>
public static class Log
{
    private static readonly Thread LogThread;
    private static readonly ConcurrentQueue<string> LogQueue; //自定义线程安全的Queue
    private static readonly object SyncRoot;
    private static readonly string FilePath;
    private static bool IsRun;
    public static bool IsWriteLog;//可以设置是否启用日志,一般只需要前期写大量的日志方便排查bug,后期程序稳定了则不需要了.异常日志建议都开启
    /// <summary>
    /// 日志类型枚举
    /// </summary>
    public enum LogType
    {
        /// <summary>
        /// 一般输出
        /// </summary>
        Trace,
        /// <summary>
        /// 警告
        /// </summary>
        Warning,
        /// <summary>
        /// 错误
        /// </summary>
        Error,
        /// <summary>
        /// SQL语句
        /// </summary>
        SQL
    }
    /// <summary>
            /// 因为线程是死循环读取队列,在没有日志数据的时候可能会消耗不必要的资源,所有当队列没有数据的时候用该类控制线程的(继续和暂停)
            /// </summary>
    private static readonly AutoResetEvent AutoReset = null;
    static Log()
    {
        AutoReset = new AutoResetEvent(false);
        SyncRoot = new object();
        FilePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "运行日志\\";       
        LogQueue = new ConcurrentQueue<string>();
        IsRun = true;
        IsWriteLog = true;
        LogThread = new Thread(WriteLog);
        LogThread.IsBackground = true;
        LogThread.Start();
    }
    //LogThread.IsBackground =false时,关闭程序时需要主动释放
    public static void Dispose()
    {
        try
        {
            if (IsRun)
            {
                IsRun = false;
                AutoReset.Set();
                AutoReset.Dispose();
            }
        }
        catch (Exception)
        {

            throw;
        }
    }
    public static void log(string msg)
    {
        try
        {
            if (!IsWriteLog) return;          
            string _msg = string.Format("{0} : {1}", DateTime.Now.ToString("HH:mm:ss:fff"), msg);
            LogQueue.Enqueue(_msg);
            if (AutoReset != null)
            {
                AutoReset.Set();
            }
        }
        catch (Exception)
        {

            throw;
        }
    } 
    public static void MemoryInfo()
    {
        try
        {
            if (!IsWriteLog) return;
            string msg;
            Process CurrentProcess = Process.GetCurrentProcess();
            //获取当前进程占用内存:
            long memory = CurrentProcess.WorkingSet64 / 1048576;
            msg = "当前进程占用内存:" + memory.ToString() + "MB;";
            string _msg = string.Format("{0} : {1}", DateTime.Now.ToString("HH:mm:ss:fff"), msg);
            LogQueue.Enqueue(_msg);
            AutoReset.Set();
        }
        catch (Exception)
        {

            throw;
        }
    }
    public static void log(string msg, LogType type)
    {
        try
        {
            if (!IsWriteLog) return;
            string _msg = string.Format("{0} {1}: {2}", DateTime.Now.ToString("HH:mm:ss:fff"), type, msg);
            LogQueue.Enqueue(_msg);
            AutoReset.Set();
        }
        catch (Exception)
        {

            throw;
        }
        
    }
    public static void log(Exception ex)
    {
        try
        {
            if (ex != null)
            {
                string _newLine = string.Empty; 
                StringBuilder _builder = new StringBuilder();
                _builder.AppendFormat("{0}: {1}{2}", DateTime.Now.ToString("HH:mm:ss:fff"), ex.Message, _newLine);
                _builder.AppendFormat("{0}{1}", ex.GetType(), _newLine);
                _builder.AppendFormat("{0}{1}", ex.Source, _newLine);
                _builder.AppendFormat("{0}{1}", ex.TargetSite, _newLine);
                _builder.AppendFormat("{0}{1}", ex.StackTrace, _newLine);
                LogQueue.Enqueue(_builder.ToString());
                AutoReset.Set();
            }
        }
        catch (Exception)
        {
            throw;
        }
        
    }
    private static void WriteLog()
    {
        try
        {          
            while (IsRun)
            {
                if (LogQueue.Count() > 0)
                {
                    string _msg;                 
                    LogQueue.TryDequeue(out _msg);
                    if (!string.IsNullOrWhiteSpace(_msg))
                    {
                        Monitor.Enter(SyncRoot);
                        if (!CreateDirectory()) continue;
                        string _path = string.Format("{0}{1}.log", FilePath, DateTime.Now.ToString("yyyy-MM-dd"));
                        Monitor.Exit(SyncRoot);
                        lock (SyncRoot)
                        {
                            if (CreateFile(_path))
                                ProcessWriteLog(_path, _msg); //写入日志到文本
                        }
                    }                  
                }
                else
                {
                    AutoReset.WaitOne();
                }
            }
        }
        catch (Exception)
        {

            throw;
        }
    }
    private static void ProcessWriteLog(string path, string msg)
    {
        try
        {
            StreamWriter _sw = File.AppendText(path);       
            _sw.WriteLine(msg);
            _sw.Flush();
            _sw.Close();
        }
        catch (Exception ex)
        {
            Debug.WriteLine(string.Format("写入日志失败,原因:{0}", ex.Message));
        }
    }
    private static bool CreateFile(string path)
    {
        bool _result = true;
        try
        {
            if (!File.Exists(path))
            {
                FileStream _files = File.Create(path);
                _files.Close();
            }
        }
        catch (Exception)
        {
            _result = false;
        }
        return _result;
    }
    private static bool CreateDirectory()
    {
        bool _result = true;
        try
        {
            if (!Directory.Exists(FilePath))
            {
                Directory.CreateDirectory(FilePath);
            }
        }
        catch (Exception)
        {
            _result = false;
        }
        return _result;
    }
}

;原文链接:https://blog.csdn.net/qq_33280495/article/details/115564513
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!

推荐图文


随机推荐