爆款云主机2核4G限时秒杀,88元/年起!
查看详情

活动

天翼云最新优惠活动,涵盖免费试用,产品折扣等,助您降本增效!
热门活动
  • 618智算钜惠季 爆款云主机2核4G限时秒杀,88元/年起!
  • 免费体验DeepSeek,上天翼云息壤 NEW 新老用户均可免费体验2500万Tokens,限时两周
  • 云上钜惠 HOT 爆款云主机全场特惠,更有万元锦鲤券等你来领!
  • 算力套餐 HOT 让算力触手可及
  • 天翼云脑AOne NEW 连接、保护、办公,All-in-One!
  • 中小企业应用上云专场 产品组合下单即享折上9折起,助力企业快速上云
  • 息壤高校钜惠活动 NEW 天翼云息壤杯高校AI大赛,数款产品享受线上订购超值特惠
  • 天翼云电脑专场 HOT 移动办公新选择,爆款4核8G畅享1年3.5折起,快来抢购!
  • 天翼云奖励推广计划 加入成为云推官,推荐新用户注册下单得现金奖励
免费活动
  • 免费试用中心 HOT 多款云产品免费试用,快来开启云上之旅
  • 天翼云用户体验官 NEW 您的洞察,重塑科技边界

智算服务

打造统一的产品能力,实现算网调度、训练推理、技术架构、资源管理一体化智算服务
智算云(DeepSeek专区)
科研助手
  • 算力商城
  • 应用商城
  • 开发机
  • 并行计算
算力互联调度平台
  • 应用市场
  • 算力市场
  • 算力调度推荐
一站式智算服务平台
  • 模型广场
  • 体验中心
  • 服务接入
智算一体机
  • 智算一体机
大模型
  • DeepSeek-R1-昇腾版(671B)
  • DeepSeek-R1-英伟达版(671B)
  • DeepSeek-V3-昇腾版(671B)
  • DeepSeek-R1-Distill-Llama-70B
  • DeepSeek-R1-Distill-Qwen-32B
  • Qwen2-72B-Instruct
  • StableDiffusion-V2.1
  • TeleChat-12B

应用商城

天翼云精选行业优秀合作伙伴及千余款商品,提供一站式云上应用服务
进入甄选商城进入云市场创新解决方案
办公协同
  • WPS云文档
  • 安全邮箱
  • EMM手机管家
  • 智能商业平台
财务管理
  • 工资条
  • 税务风控云
企业应用
  • 翼信息化运维服务
  • 翼视频云归档解决方案
工业能源
  • 智慧工厂_生产流程管理解决方案
  • 智慧工地
建站工具
  • SSL证书
  • 新域名服务
网络工具
  • 翼云加速
灾备迁移
  • 云管家2.0
  • 翼备份
资源管理
  • 全栈混合云敏捷版(软件)
  • 全栈混合云敏捷版(一体机)
行业应用
  • 翼电子教室
  • 翼智慧显示一体化解决方案

合作伙伴

天翼云携手合作伙伴,共创云上生态,合作共赢
天翼云生态合作中心
  • 天翼云生态合作中心
天翼云渠道合作伙伴
  • 天翼云代理渠道合作伙伴
天翼云服务合作伙伴
  • 天翼云集成商交付能力认证
天翼云应用合作伙伴
  • 天翼云云市场合作伙伴
  • 天翼云甄选商城合作伙伴
天翼云技术合作伙伴
  • 天翼云OpenAPI中心
  • 天翼云EasyCoding平台
天翼云培训认证
  • 天翼云学堂
  • 天翼云市场商学院
天翼云合作计划
  • 云汇计划
天翼云东升计划
  • 适配中心
  • 东升计划
  • 适配互认证

开发者

开发者相关功能入口汇聚
技术社区
  • 专栏文章
  • 互动问答
  • 技术视频
资源与工具
  • OpenAPI中心
开放能力
  • EasyCoding敏捷开发平台
培训与认证
  • 天翼云学堂
  • 天翼云认证
魔乐社区
  • 魔乐社区

支持与服务

为您提供全方位支持与服务,全流程技术保障,助您轻松上云,安全无忧
文档与工具
  • 文档中心
  • 新手上云
  • 自助服务
  • OpenAPI中心
定价
  • 价格计算器
  • 定价策略
基础服务
  • 售前咨询
  • 在线支持
  • 在线支持
  • 工单服务
  • 建议与反馈
  • 用户体验官
  • 服务保障
  • 客户公告
  • 会员中心
增值服务
  • 红心服务
  • 首保服务
  • 客户支持计划
  • 专家技术服务
  • 备案管家

了解天翼云

天翼云秉承央企使命,致力于成为数字经济主力军,投身科技强国伟大事业,为用户提供安全、普惠云服务
品牌介绍
  • 关于天翼云
  • 智算云
  • 天翼云4.0
  • 新闻资讯
  • 天翼云APP
基础设施
  • 全球基础设施
  • 信任中心
最佳实践
  • 精选案例
  • 超级探访
  • 云杂志
  • 分析师和白皮书
  • 天翼云·创新直播间
市场活动
  • 2025智能云生态大会
  • 2024智算云生态大会
  • 2023云生态大会
  • 2022云生态大会
  • 天翼云中国行
天翼云
  • 活动
  • 智算服务
  • 产品
  • 解决方案
  • 应用商城
  • 合作伙伴
  • 开发者
  • 支持与服务
  • 了解天翼云
      • 文档
      • 控制中心
      • 备案
      • 管理中心

      C#写日志工具类(旧版)

      首页 知识中心 软件开发 文章详情页

      C#写日志工具类(旧版)

      2023-03-31 06:13:51 阅读次数:157

      工具,日志

      CPU:i5-8265U 硬盘:固态硬盘 测试结果:每秒写入文件大约1万到3万条日志,每条日志的字符串长度是140多个字符

      支持多线程并发,支持多进程并发,支持按文件大小分隔日志文件

      LogUtil.cs代码:

      C#写日志工具类(旧版)C#写日志工具类(旧版)

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

      namespace Utils
      {
      /// <summary>
      /// 写日志类
      /// </summary>
      public class LogUtil
      {
      #region 字段
      private static string _path = null;

      private static Mutex _mutex = new Mutex(false, "LogUtil.Mutex.180740C3B1C44D428683D35F84F97E22");

      private static ConcurrentDictionary<string, int> _dictIndex = new ConcurrentDictionary<string, int>();
      private static ConcurrentDictionary<string, long> _dictSize = new ConcurrentDictionary<string, long>();
      private static ConcurrentDictionary<string, FileStream> _dictStream = new ConcurrentDictionary<string, FileStream>();
      private static ConcurrentDictionary<string, StreamWriter> _dictWriter = new ConcurrentDictionary<string, StreamWriter>();

      private static ConcurrentDictionary<string, string> _dictPathFolders = new ConcurrentDictionary<string, string>();

      private static TaskSchedulerEx _scheduler = new TaskSchedulerEx(2, 2);

      private static int _fileSize = 10 * 1024 * 1024; //日志分隔文件大小
      #endregion

      #region 写文件
      /// <summary>
      /// 写文件
      /// </summary>
      private static void WriteFile(LogType logType, string log, string path)
      {
      try
      {
      FileStream fs = null;
      StreamWriter sw = null;

      if (!(_dictStream.TryGetValue(logType.ToString() + path, out fs) && _dictWriter.TryGetValue(logType.ToString() + path, out sw)))
      {
      foreach (string key in _dictWriter.Keys)
      {
      if (key.StartsWith(logType.ToString()))
      {
      StreamWriter item;
      _dictWriter.TryRemove(key, out item);
      item.Close();
      }
      }

      foreach (string key in _dictStream.Keys)
      {
      if (key.StartsWith(logType.ToString()))
      {
      FileStream item;
      _dictStream.TryRemove(key, out item);
      item.Close();
      }
      }

      if (!Directory.Exists(Path.GetDirectoryName(path)))
      {
      Directory.CreateDirectory(Path.GetDirectoryName(path));
      }

      fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
      sw = new StreamWriter(fs);
      _dictWriter.TryAdd(logType.ToString() + path, sw);
      _dictStream.TryAdd(logType.ToString() + path, fs);
      }

      fs.Seek(0, SeekOrigin.End);
      sw.WriteLine(log);
      sw.Flush();
      fs.Flush();
      }
      catch (Exception ex)
      {
      string str = ex.Message;
      }
      }
      #endregion

      #region 生成日志文件路径
      /// <summary>
      /// 生成日志文件路径
      /// </summary>
      private static string CreateLogPath(LogType logType, string log)
      {
      try
      {
      if (_path == null)
      {
      UriBuilder uri = new UriBuilder(Assembly.GetExecutingAssembly().CodeBase);
      _path = Path.GetDirectoryName(Uri.UnescapeDataString(uri.Path));
      }

      string pathFolder = Path.Combine(_path, "Log\\" + logType.ToString() + "\\");
      if (!_dictPathFolders.ContainsKey(pathFolder))
      {
      if (!Directory.Exists(Path.GetDirectoryName(pathFolder)))
      {
      Directory.CreateDirectory(Path.GetDirectoryName(pathFolder));
      }
      _dictPathFolders.TryAdd(pathFolder, pathFolder);
      }

      int currentIndex;
      long size;
      string strNow = DateTime.Now.ToString("yyyyMMdd");
      string strKey = pathFolder + strNow;
      if (!(_dictIndex.TryGetValue(strKey, out currentIndex) && _dictSize.TryGetValue(strKey, out size)))
      {
      _dictIndex.Clear();
      _dictSize.Clear();

      GetIndexAndSize(pathFolder, strNow, out currentIndex, out size);
      if (size >= _fileSize) currentIndex++;
      _dictIndex.TryAdd(strKey, currentIndex);
      _dictSize.TryAdd(strKey, size);
      }

      int index = _dictIndex[strKey];
      string logPath = Path.Combine(pathFolder, strNow + (index == 1 ? "" : "_" + index.ToString()) + ".txt");

      _dictSize[strKey] += Encoding.UTF8.GetByteCount(log);
      if (_dictSize[strKey] > _fileSize)
      {
      _dictIndex[strKey]++;
      _dictSize[strKey] = 0;
      }

      return logPath;
      }
      catch (Exception ex)
      {
      string str = ex.Message;
      return null;
      }
      }
      #endregion

      #region 拼接日志内容
      /// <summary>
      /// 拼接日志内容
      /// </summary>
      private static string CreateLogString(LogType logType, string log)
      {
      return string.Format(@"{0} {1} {2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), ("[" + logType.ToString() + "]").PadRight(7, ' '), log);
      }
      #endregion

      #region 获取初始Index和Size
      /// <summary>
      /// 获取初始Index和Size
      /// </summary>
      private static void GetIndexAndSize(string pathFolder, string strNow, out int index, out long size)
      {
      index = 1;
      size = 0;
      Regex regex = new Regex(strNow + "_*(\\d*).txt");
      string[] fileArr = Directory.GetFiles(pathFolder);
      string currentFile = null;
      foreach (string file in fileArr)
      {
      Match match = regex.Match(file);
      if (match.Success)
      {
      string str = match.Groups[1].Value;
      if (!string.IsNullOrWhiteSpace(str))
      {
      int temp = Convert.ToInt32(str);
      if (temp > index)
      {
      index = temp;
      currentFile = file;
      }
      }
      else
      {
      index = 1;
      currentFile = file;
      }
      }
      }

      if (currentFile != null)
      {
      FileInfo fileInfo = new FileInfo(currentFile);
      size = fileInfo.Length;
      }
      }
      #endregion

      #region 写调试日志
      /// <summary>
      /// 写调试日志
      /// </summary>
      public static Task Debug(string log)
      {
      return Task.Factory.StartNew(() =>
      {
      try
      {
      _mutex.WaitOne();

      log = CreateLogString(LogType.Debug, log);
      string path = CreateLogPath(LogType.Debug, log);
      WriteFile(LogType.Debug, log, path);
      }
      catch (Exception ex)
      {
      string str = ex.Message;
      }
      finally
      {
      _mutex.ReleaseMutex();
      }
      }, CancellationToken.None, TaskCreationOptions.None, _scheduler);
      }
      #endregion

      #region 写错误日志
      public static Task Error(Exception ex, string log = null)
      {
      return Error(string.IsNullOrEmpty(log) ? ex.Message + "\r\n" + ex.StackTrace : (log + ":") + ex.Message + "\r\n" + ex.StackTrace);
      }

      /// <summary>
      /// 写错误日志
      /// </summary>
      public static Task Error(string log)
      {
      return Task.Factory.StartNew(() =>
      {
      try
      {
      _mutex.WaitOne();

      log = CreateLogString(LogType.Error, log);
      string path = CreateLogPath(LogType.Error, log);
      WriteFile(LogType.Error, log, path);
      }
      catch (Exception ex)
      {
      string str = ex.Message;
      }
      finally
      {
      _mutex.ReleaseMutex();
      }
      }, CancellationToken.None, TaskCreationOptions.None, _scheduler);
      }
      #endregion

      #region 写操作日志
      /// <summary>
      /// 写操作日志
      /// </summary>
      public static Task Log(string log)
      {
      return Task.Factory.StartNew(() =>
      {
      try
      {
      _mutex.WaitOne();

      log = CreateLogString(LogType.Info, log);
      string path = CreateLogPath(LogType.Info, log);
      WriteFile(LogType.Info, log, path);
      }
      catch (Exception ex)
      {
      string str = ex.Message;
      }
      finally
      {
      _mutex.ReleaseMutex();
      }
      }, CancellationToken.None, TaskCreationOptions.None, _scheduler);
      }
      #endregion

      }

      #region 日志类型
      /// <summary>
      /// 日志类型
      /// </summary>
      public enum LogType
      {
      Debug,

      Info,

      Error
      }
      #endregion

      }

      View Code

      依赖的TaskSchedulerEx.cs代码:

      C#写日志工具类(旧版)C#写日志工具类(旧版)

      using System;
      using System.Collections.Concurrent;
      using System.Collections.Generic;
      using System.Linq;
      using System.Runtime.InteropServices;
      using System.Text;
      using System.Threading;
      using System.Threading.Tasks;

      namespace Utils
      {
      /// <summary>
      /// TaskScheduler扩展
      /// 每个实例都是独立线程池
      /// </summary>
      public class TaskSchedulerEx : TaskScheduler, IDisposable
      {
      #region 外部方法
      [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
      public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
      #endregion

      #region 变量属性事件
      private ConcurrentQueue<Task> _tasks = new ConcurrentQueue<Task>();
      private int _coreThreadCount = 0;
      private int _maxThreadCount = 0;
      private int _auxiliaryThreadTimeOut = 20000; //辅助线程释放时间
      private int _activeThreadCount = 0;
      private System.Timers.Timer _timer;
      private object _lockCreateTimer = new object();
      private bool _run = true;
      private AutoResetEvent _evt = new AutoResetEvent(false);

      /// <summary>
      /// 活跃线程数
      /// </summary>
      public int ActiveThreadCount
      {
      get { return _activeThreadCount; }
      }

      /// <summary>
      /// 核心线程数
      /// </summary>
      public int CoreThreadCount
      {
      get { return _coreThreadCount; }
      }

      /// <summary>
      /// 最大线程数
      /// </summary>
      public int MaxThreadCount
      {
      get { return _maxThreadCount; }
      }
      #endregion

      #region 构造函数
      /// <summary>
      /// TaskScheduler扩展
      /// 每个实例都是独立线程池
      /// </summary>
      /// <param name="coreThreadCount">核心线程数(大于或等于0,不宜过大)(如果是一次性使用,则设置为0比较合适)</param>
      /// <param name="maxThreadCount">最大线程数</param>
      public TaskSchedulerEx(int coreThreadCount = 10, int maxThreadCount = 20)
      {
      _maxThreadCount = maxThreadCount;
      CreateCoreThreads(coreThreadCount);
      }
      #endregion

      #region override GetScheduledTasks
      protected override IEnumerable<Task> GetScheduledTasks()
      {
      return _tasks;
      }
      #endregion

      #region override TryExecuteTaskInline
      protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
      {
      return false;
      }
      #endregion

      #region override QueueTask
      protected override void QueueTask(Task task)
      {
      CreateTimer();
      _tasks.Enqueue(task);
      _evt.Set();
      }
      #endregion

      #region 资源释放
      /// <summary>
      /// 资源释放
      /// 队列中尚未执行的任务不再执行
      /// </summary>
      public void Dispose()
      {
      _run = false;

      if (_timer != null)
      {
      _timer.Stop();
      _timer.Dispose();
      _timer = null;
      }

      while (_activeThreadCount > 0)
      {
      _evt.Set();
      }
      }
      #endregion

      #region 创建核心线程池
      /// <summary>
      /// 创建核心线程池
      /// </summary>
      private void CreateCoreThreads(int? coreThreadCount = null)
      {
      if (coreThreadCount != null) _coreThreadCount = coreThreadCount.Value;

      for (int i = 0; i < _coreThreadCount; i++)
      {
      Interlocked.Increment(ref _activeThreadCount);
      Thread thread = null;
      thread = new Thread(new ThreadStart(() =>
      {
      Task task;
      while (_run)
      {
      if (_tasks.TryDequeue(out task))
      {
      TryExecuteTask(task);
      }
      else
      {
      _evt.WaitOne();
      }
      }
      Interlocked.Decrement(ref _activeThreadCount);
      if (_activeThreadCount == 0)
      {
      GC.Collect();
      GC.WaitForPendingFinalizers();
      if (Environment.OSVersion.Platform == PlatformID.Win32NT)
      {
      SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
      }
      }
      }));
      thread.IsBackground = true;
      thread.Start();
      }
      }
      #endregion

      #region 创建辅助线程
      /// <summary>
      /// 创建辅助线程
      /// </summary>
      private void CreateThread()
      {
      Interlocked.Increment(ref _activeThreadCount);
      Thread thread = null;
      thread = new Thread(new ThreadStart(() =>
      {
      Task task;
      DateTime dt = DateTime.Now;
      while (_run && DateTime.Now.Subtract(dt).TotalMilliseconds < _auxiliaryThreadTimeOut)
      {
      if (_tasks.TryDequeue(out task))
      {
      TryExecuteTask(task);
      dt = DateTime.Now;
      }
      else
      {
      _evt.WaitOne(_auxiliaryThreadTimeOut);
      }
      }
      Interlocked.Decrement(ref _activeThreadCount);
      if (_activeThreadCount == _coreThreadCount)
      {
      GC.Collect();
      GC.WaitForPendingFinalizers();
      if (Environment.OSVersion.Platform == PlatformID.Win32NT)
      {
      SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
      }
      }
      }));
      thread.IsBackground = true;
      thread.Start();
      }
      #endregion

      #region 创建定时器
      private void CreateTimer()
      {
      if (_timer == null) //_timer不为空时,跳过,不走lock,提升性能
      {
      if (_activeThreadCount >= _coreThreadCount && _activeThreadCount < _maxThreadCount) //活跃线程数达到最大线程数时,跳过,不走lock,提升性能
      {
      lock (_lockCreateTimer)
      {
      if (_timer == null)
      {
      _timer = new System.Timers.Timer();
      _timer.Interval = _coreThreadCount == 0 ? 1 : 500;
      _timer.Elapsed += (s, e) =>
      {
      if (_activeThreadCount >= _coreThreadCount && _activeThreadCount < _maxThreadCount)
      {
      if (_tasks.Count > 0)
      {
      if (_timer.Interval != 20) _timer.Interval = 20;
      CreateThread();
      }
      else
      {
      if (_timer.Interval != 500) _timer.Interval = 500;
      }
      }
      else
      {
      if (_timer != null)
      {
      _timer.Stop();
      _timer.Dispose();
      _timer = null;
      }
      }
      };
      _timer.Start();
      }
      }
      }
      }
      }
      #endregion

      #region 全部取消
      /// <summary>
      /// 全部取消
      /// 取消队列中尚未执行的任务
      /// </summary>
      public void CancelAll()
      {
      Task tempTask;
      while (_tasks.TryDequeue(out tempTask)) { }
      }
      #endregion

      }
      }

      View Code

      依赖的RunHelper.cs代码:

      C#写日志工具类(旧版)C#写日志工具类(旧版)

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.Threading;
      using System.Threading.Tasks;

      namespace Utils
      {
      /// <summary>
      /// 线程工具类
      /// </summary>
      public static class RunHelper
      {
      #region 变量属性事件

      #endregion

      #region 线程中执行
      /// <summary>
      /// 线程中执行
      /// </summary>
      public static Task Run(this TaskScheduler scheduler, Action<object> doWork, object arg = null, Action<Exception> errorAction = null)
      {
      return Task.Factory.StartNew((obj) =>
      {
      try
      {
      doWork(obj);
      }
      catch (Exception ex)
      {
      if (errorAction != null) errorAction(ex);
      LogUtil.Error(ex, "ThreadUtil.Run错误");
      }
      }, arg, CancellationToken.None, TaskCreationOptions.None, scheduler);
      }
      #endregion

      #region 线程中执行
      /// <summary>
      /// 线程中执行
      /// </summary>
      public static Task Run(this TaskScheduler scheduler, Action doWork, Action<Exception> errorAction = null)
      {
      return Task.Factory.StartNew(() =>
      {
      try
      {
      doWork();
      }
      catch (Exception ex)
      {
      if (errorAction != null) errorAction(ex);
      LogUtil.Error(ex, "ThreadUtil.Run错误");
      }
      }, CancellationToken.None, TaskCreationOptions.None, scheduler);
      }
      #endregion

      #region 线程中执行
      /// <summary>
      /// 线程中执行
      /// </summary>
      public static Task<T> Run<T>(this TaskScheduler scheduler, Func<object, T> doWork, object arg = null, Action<Exception> errorAction = null)
      {
      return Task.Factory.StartNew<T>((obj) =>
      {
      try
      {
      return doWork(obj);
      }
      catch (Exception ex)
      {
      if (errorAction != null) errorAction(ex);
      LogUtil.Error(ex, "ThreadUtil.Run错误");
      return default(T);
      }
      }, arg, CancellationToken.None, TaskCreationOptions.None, scheduler);
      }
      #endregion

      #region 线程中执行
      /// <summary>
      /// 线程中执行
      /// </summary>
      public static Task<T> Run<T>(this TaskScheduler scheduler, Func<T> doWork, Action<Exception> errorAction = null)
      {
      return Task.Factory.StartNew<T>(() =>
      {
      try
      {
      return doWork();
      }
      catch (Exception ex)
      {
      if (errorAction != null) errorAction(ex);
      LogUtil.Error(ex, "ThreadUtil.Run错误");
      return default(T);
      }
      }, CancellationToken.None, TaskCreationOptions.None, scheduler);
      }
      #endregion

      #region 线程中执行
      /// <summary>
      /// 线程中执行
      /// </summary>
      public static async Task<T> RunAsync<T>(this TaskScheduler scheduler, Func<object, T> doWork, object arg = null, Action<Exception> errorAction = null)
      {
      return await Task.Factory.StartNew<T>((obj) =>
      {
      try
      {
      return doWork(obj);
      }
      catch (Exception ex)
      {
      if (errorAction != null) errorAction(ex);
      LogUtil.Error(ex, "ThreadUtil.Run错误");
      return default(T);
      }
      }, arg, CancellationToken.None, TaskCreationOptions.None, scheduler);
      }
      #endregion

      #region 线程中执行
      /// <summary>
      /// 线程中执行
      /// </summary>
      public static async Task<T> RunAsync<T>(this TaskScheduler scheduler, Func<T> doWork, Action<Exception> errorAction = null)
      {
      return await Task.Factory.StartNew<T>(() =>
      {
      try
      {
      return doWork();
      }
      catch (Exception ex)
      {
      if (errorAction != null) errorAction(ex);
      LogUtil.Error(ex, "ThreadUtil.Run错误");
      return default(T);
      }
      }, CancellationToken.None, TaskCreationOptions.None, scheduler);
      }
      #endregion

      }
      }

      View Code

      测试代码:

      C#写日志工具类(旧版)C#写日志工具类(旧版)

      using System;
      using System.Collections.Generic;
      using System.ComponentModel;
      using System.Data;
      using System.Diagnostics;
      using System.Drawing;
      using System.Linq;
      using System.Text;
      using System.Threading;
      using System.Threading.Tasks;
      using System.Windows.Forms;
      using Utils;

      namespace LogUtilTest
      {
      public partial class Form1 : Form
      {
      public Form1()
      {
      InitializeComponent();
      }

      private void button1_Click(object sender, EventArgs e)
      {
      Task.Factory.StartNew(() =>
      {
      int n = 100000;
      string processId = Process.GetCurrentProcess().Id.ToString().PadLeft(8, ' ');
      List<Task> taskList = new List<Task>();
      string str = " abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcda3.1415bcdabcdabcdabcdabc@#$%^&dabcdabcdabcdabcdabcdabcdabcdabcd";
      DateTime dtStart = DateTime.Now;
      for (int i = 1; i <= n; i++)
      {
      Task task = LogUtil.Log("ProcessId:【" + processId + "】 测试" + i.ToString().PadLeft(8, '0') + str);
      taskList.Add(task);
      task = LogUtil.Debug("ProcessId:【" + processId + "】 测试" + i.ToString().PadLeft(8, '0') + str);
      taskList.Add(task);
      }
      Task.WaitAll(taskList.ToArray());

      double sec = DateTime.Now.Subtract(dtStart).TotalSeconds;
      MessageBox.Show(n + "条日志完成,耗时" + sec.ToString("0.000") + "秒");
      });
      }
      }
      }

      View Code

      测试结果截图:

      C#写日志工具类(旧版)

      版权声明:本文内容来自第三方投稿或授权转载,原文地址:https://blog.51cto.com/u_5496753/5263755,作者:0611163,版权归原作者所有。本网站转在其作品的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如因作品内容、版权等问题需要同本网站联系,请发邮件至ctyunbbs@chinatelecom.cn沟通。

      上一篇:Python之求阶乘

      下一篇:flask-01-http通信的回顾

      相关文章

      2025-05-19 09:05:01

      【Linux】HDP集群日志配置和日志删除脚本

      HDP 集群 默认安装的,日志放在数据盘,但是 namenode和snamenode的数据盘本身不大只有 500G,在不经意间 数据盘被日志装满,首先从集群配置着手。

      2025-05-19 09:05:01
      log4j , 日志 , 集群
      2025-05-19 09:04:38

      DataGuard GAP 修复3-- 归档日志不存在

      DataGuard GAP 修复3-- 归档日志不存在

      2025-05-19 09:04:38
      归档 , 日志
      2025-05-14 10:03:13

      【Mybatis】-防止SQL注入

      【Mybatis】-防止SQL注入

      2025-05-14 10:03:13
      SQL , 执行 , 日志 , 注入 , 缓存 , 编译 , 语句
      2025-05-14 10:02:48

      SQL Server 事务日志体系结构1--基本术语

      事务包括对数据库的一次更改或一系列更改。它有一个明确开始和明确结束。开始时使用BEGIN TRANSACTION语句,或者SQL Server会自动为您开始一个事务。

      2025-05-14 10:02:48
      Server , SQL , 事务 , 数据库 , 日志 , 磁盘
      2025-05-13 09:53:23

      AIGC工具的使用测评:代码分析与原理实现

      AIGC(Artificial Intelligence Guided Coding)工具是一种基于人工智能技术的开发辅助工具,旨在通过智能化的代码分析和预测,为开发者提供更快速、准确的开发体验。

      2025-05-13 09:53:23
      AIGC , 代码 , 工具 , 开发者 , 模型 , 生成 , 示例
      2025-05-13 09:51:17

      rac dg节点2在修改完alert_oracle_sid.log文件名,主库切换日志后备库节点2不产生新的日志文件

      rac dg节点2在修改完alert_oracle_sid.log文件名,主库切换日志后备库节点2不产生新的日志文件

      2025-05-13 09:51:17
      dg , rac , 日志 , 节点
      2025-05-13 09:51:17

      搭建ogg时无法启动目标端复制进程,告警日志报错OGG-02091

      搭建ogg时无法启动目标端复制进程,告警日志报错OGG-02091

      2025-05-13 09:51:17
      ogg , OGG , 报错 , 日志
      2025-05-09 08:51:09

      【Linux 从基础到进阶】系统资源监控与报警

      【Linux 从基础到进阶】系统资源监控与报警

      2025-05-09 08:51:09
      CPU , 工具 , 监控
      2025-05-09 08:51:09

      RestTemplate请求UnknownContentTypeException:no suitable HttpMessageConverter异常

      RestTemplate请求UnknownContentTypeException:no suitable HttpMessageConverter异常

      2025-05-09 08:51:09
      html , RestTemplate , text , 日志 , 格式
      2025-05-08 09:04:49

      MySQL-备份+日志:介质故障与数据库恢复

      MySQL-备份+日志:介质故障与数据库恢复

      2025-05-08 09:04:49
      mysql , MySQL , 备份 , 恢复 , 数据库 , 文件 , 日志
      查看更多
      推荐标签

      作者介绍

      天翼云小翼
      天翼云用户

      文章

      33561

      阅读量

      5265726

      查看更多

      最新文章

      AIGC工具的使用测评:代码分析与原理实现

      2025-05-13 09:53:23

      RestTemplate请求UnknownContentTypeException:no suitable HttpMessageConverter异常

      2025-05-09 08:51:09

      SpringBoot3基础用法

      2025-05-07 09:09:52

      java应用性能调优之详解System的gc垃圾回收方法

      2025-04-09 09:14:24

      利用自定义注解优化操作日志记录

      2025-03-28 07:41:55

      Java 工具类库:Hutool使用说明

      2025-03-27 10:12:02

      查看更多

      热门文章

      【Java】日志的概念

      2023-07-26 08:09:07

      Spring 日志输出错误字符 -e[0;39m e[2m[

      2023-07-27 06:49:39

      SpringBoot日志基本操作

      2024-09-25 10:14:09

      3.3 日志

      2023-02-16 09:37:42

      Spring Boot 项目如何统一结果,统一异常,统一日志

      2024-09-25 10:14:21

      AIGC工具使用测评与个人AI作画体验分享

      2024-12-23 09:17:51

      查看更多

      热门标签

      java Java python 编程开发 代码 开发语言 算法 线程 Python html 数组 C++ 元素 javascript c++
      查看更多

      相关产品

      弹性云主机

      随时自助获取、弹性伸缩的云服务器资源

      天翼云电脑(公众版)

      便捷、安全、高效的云电脑服务

      对象存储

      高品质、低成本的云上存储服务

      云硬盘

      为云上计算资源提供持久性块存储

      查看更多

      随机文章

      SpringBoot3基础用法

      17 案例:开发shell采集脚本

      Springboot入门三十六,logback配置

      日志管理演进:从基础到创新

      java项目技术方案

      SpringBoot日志基本操作

      • 7*24小时售后
      • 无忧退款
      • 免费备案
      • 专家服务
      售前咨询热线
      400-810-9889转1
      关注天翼云
      • 旗舰店
      • 天翼云APP
      • 天翼云微信公众号
      服务与支持
      • 备案中心
      • 售前咨询
      • 智能客服
      • 自助服务
      • 工单管理
      • 客户公告
      • 涉诈举报
      账户管理
      • 管理中心
      • 订单管理
      • 余额管理
      • 发票管理
      • 充值汇款
      • 续费管理
      快速入口
      • 天翼云旗舰店
      • 文档中心
      • 最新活动
      • 免费试用
      • 信任中心
      • 天翼云学堂
      云网生态
      • 甄选商城
      • 渠道合作
      • 云市场合作
      了解天翼云
      • 关于天翼云
      • 天翼云APP
      • 服务案例
      • 新闻资讯
      • 联系我们
      热门产品
      • 云电脑
      • 弹性云主机
      • 云电脑政企版
      • 天翼云手机
      • 云数据库
      • 对象存储
      • 云硬盘
      • Web应用防火墙
      • 服务器安全卫士
      • CDN加速
      热门推荐
      • 云服务备份
      • 边缘安全加速平台
      • 全站加速
      • 安全加速
      • 云服务器
      • 云主机
      • 智能边缘云
      • 应用编排服务
      • 微服务引擎
      • 共享流量包
      更多推荐
      • web应用防火墙
      • 密钥管理
      • 等保咨询
      • 安全专区
      • 应用运维管理
      • 云日志服务
      • 文档数据库服务
      • 云搜索服务
      • 数据湖探索
      • 数据仓库服务
      友情链接
      • 中国电信集团
      • 189邮箱
      • 天翼企业云盘
      • 天翼云盘
      ©2025 天翼云科技有限公司版权所有 增值电信业务经营许可证A2.B1.B2-20090001
      公司地址:北京市东城区青龙胡同甲1号、3号2幢2层205-32室
      • 用户协议
      • 隐私政策
      • 个人信息保护
      • 法律声明
      备案 京公网安备11010802043424号 京ICP备 2021034386号