当前位置: 首页 > news >正文

简单实现log记录保存到文本和数据库

简单保存记录到txt,sqlite数据库,以及console监控记录

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Data.SQLite;
using System.IO;namespace NlogFrame
{public enum  LogType{Trace,Consl,Debug,Info,Warn,Error,Fatal}public class Log{/// <summary>/// 最大缓存数/// </summary>[Browsable(true)]public static int MaxTempListCnt { get; set; } = 300;[Browsable(true)]public static LogType MinLevel { get; set; } = 0;[Browsable(true)]public static bool DebugEnable { get; set; } = true;[Browsable(true)]public static bool TraceEnable { get; set; } = true;[Browsable(true)]public static bool WarnEnable { get; set; } = true;static bool _ConsoleEnable = false;static TextWriter originalOut = null;[Browsable(true)]public static bool ConsoleEnable{get { return _ConsoleEnable; }set{_ConsoleEnable = value;if (value == true){if (originalOut == null){originalOut = Console.Out;}Console.SetOut(logConsole);}else{if (originalOut != null){Console.SetOut(originalOut);originalOut = null;}}}}[Browsable(true)]public string Name { get; set; } = "";static LogConsole logConsole = new LogConsole();public static List<LogInfo> TempLogInfoList => _TempLogInfoList;static List<LogInfo> _TempLogInfoList;public Log(string name){Name = name;}public void Error(string msg){if ((int)LogType.Error >= (int)MinLevel){//logger.Error(msg);AddLog(new LogInfo(DateTime.Now, LogType.Error, msg));}}public void Consl(string msg){if ((int)LogType.Consl >= (int)MinLevel){//logger.Error(msg);AddLog(new LogInfo(DateTime.Now, LogType.Consl, msg));}}public void Trace(string msg){if ((int)LogType.Trace >= MinLevel){// logger.Trace(msg);AddLog(new LogInfo(DateTime.Now, LogType.Trace, msg));}}public void Warn (string msg){if ((int)LogType.Warn >= (int)MinLevel){// logger.Warn(msg);AddLog(new LogInfo(DateTime.Now, LogType.Warn, msg));}}public void Info(string msg){if ((int)LogType.Info >= (int)MinLevel){//logger.Info(msg);AddLog(new LogInfo(DateTime.Now, LogType.Info, msg));}}public void Debug(string msg){if ((int)LogType.Debug >= (int)MinLevel){// logger.Debug(msg);AddLog(new LogInfo(DateTime.Now, LogType.Debug, msg));}}public void Fatal(string msg){if ((int)LogType.Fatal >= (int)MinLevel){//logger.Fatal(msg);AddLog(new LogInfo(DateTime.Now, LogType.Fatal, msg));}}public void WriteLogTxt(LogInfo info){// 定义日志文件的路径  string logFilePath = Environment.CurrentDirectory + "\\logs\\log-" + DateTime.Now.Date.ToString("yyyy-mm-dd") + ".txt";if (!Directory.Exists(Environment.CurrentDirectory + "\\logs\\"))Directory.CreateDirectory(Environment.CurrentDirectory + "\\logs\\");// 使用StreamWriter写入日志  // 如果文件不存在,它将被创建;如果文件已存在,则默认是追加模式  using (StreamWriter writer = new StreamWriter(logFilePath, true)) // 第二个参数为true表示追加模式  {// 写入日志信息  writer.WriteLine(info.ToString());// 你可以继续写入更多的日志信息  }}public void WriteLogSqlite(LogInfo info){// 定义日志文件的路径  string logFilePath = Environment.CurrentDirectory + "\\logs\\db-" + DateTime.Now.Date.ToString("yyyy-mm-dd") + ".db";if (!Directory.Exists(Environment.CurrentDirectory + "\\logs\\"))Directory.CreateDirectory(Environment.CurrentDirectory + "\\logs\\");// 创建数据库(如果尚不存在)  using (var connection = new SQLiteConnection($"Data Source={logFilePath}")){connection.Open();// 创建一个表(如果尚不存在)  string createTableSql = @"  CREATE TABLE IF NOT EXISTS Log (  Id INTEGER PRIMARY KEY AUTOINCREMENT,  Time TEXT NOT NULL,  Name TEXT , Type INTEGER , Message TEXT)";using (var command = new SQLiteCommand(createTableSql, connection)){command.ExecuteNonQuery();}// 插入数据  string insertSql = "INSERT INTO Log (Time,Name ,Type , Message) VALUES (@Time,@Name,@Type, @Message)";using (var command = new SQLiteCommand(insertSql, connection)){command.Parameters.AddWithValue("@Time", info.Time.ToString("yyyy-MM-dd HH:mm:ss.fff"));command.Parameters.AddWithValue("@Name", info.Name);command.Parameters.AddWithValue("@Type", info.Type);command.Parameters.AddWithValue("@Message",info.Message);command.ExecuteNonQuery();}}}public void DeleteFile(){// 指定你想要遍历的文件夹路径  string folderPath = @"C:\你的文件夹路径";// 获取文件夹中的所有文件  string[] files = Directory.GetFiles(folderPath);// 遍历文件  foreach (string file in files){// 获取文件的创建时间  FileInfo fileInfo = new FileInfo(file);DateTime creationTime = fileInfo.CreationTime;// 计算自文件创建以来的天数  TimeSpan span = DateTime.Now - creationTime;double days = span.TotalDays;// 如果文件创建时间超过20天  if (days > 20){try{// 删除文件  File.Delete(file);//Console.WriteLine($"已删除文件: {file}");}catch (Exception ex){// 处理删除文件时可能出现的异常,例如文件正在使用中  Console.WriteLine($"无法删除文件: {file}. 错误: {ex.Message}");}}}Console.WriteLine("处理完成。");Console.ReadKey(); // 暂停,以便查看输出  }private void AddLog(LogInfo info){info.Name = Name;WriteLogTxt(info);WriteLogSqlite(info);if (_TempLogInfoList == null){_TempLogInfoList = new List<LogInfo>();}while (_TempLogInfoList.Count > MaxTempListCnt){_TempLogInfoList.RemoveAt(0);}_TempLogInfoList.Add(info);}}public class LogInfo{[Description("时间")]public DateTime Time { get; set; }[Description("类型")]public LogType Type { get; set; }[Description("对象")]public string Name { get; set; }[Description("信息")]public string Message { get; set; }public LogInfo(DateTime dateTime, LogType type, string msg){Time = dateTime;Type = type;Message = msg;}public override string ToString() => Time.ToString("yyyy-MM-dd HH:mm:ss.fff") + " | " + Type + " | " + Name + " | " + Message;}public class LogConsole : TextWriter{private StringBuilder _sb = new StringBuilder();public override Encoding Encoding => throw new NotImplementedException();public override void WriteLine(string value){Log console = new Log("控制台");//_sb.AppendLine(value);// 这里可以添加额外的逻辑,比如记录到文件或数据库  console.Consl(value);Console.WriteLine($"Intercepted: {value}");//Console.WriteLine($"Intercepted: {value}"); // 仅为了演示  }// 你可以根据需要实现其他重写的方法  // 一个方法用于获取或清空收集的输出  public string GetAndClearOutput(){string output = _sb.ToString();_sb.Clear();return output;}}
}
http://www.lryc.cn/news/449452.html

相关文章:

  • 敏感字段加密 - 华为OD统一考试(E卷)
  • go 安装三方库
  • Java 中的 volatile和synchronized和 ReentrantLock区别讲解和案例示范
  • 从GDAL中 读取遥感影像的信息
  • 算法闭关修炼百题计划(一)
  • vue3实现打字机的效果,可以换行
  • 【如何学习操作系统】——学会学习的艺术
  • stm32 flash无法擦除
  • Android—ANR日志分析
  • 9.29 LeetCode 3304、3300、3301
  • 近万字深入讲解iOS常见锁及线程安全
  • linux创建固定大小的文件夹用于测试
  • 大模型学习路线:这会是你见过最全最新的大模型学习路线【2024最新】
  • 了解云计算工作负载保护的重要性,确保数据和应用程序安全
  • Swagger3基本使用
  • 如何借助Java批量操作Excel文件?
  • JUC并发编程_Lock锁
  • Unity中的功能解释(数学位置相关和事件)
  • ElementPlus---Timeline 时间线组件使用示例
  • 推荐4款2024年大家都在用的高质量翻译器。
  • Mybatis 返回 Map 对象
  • Vue3(三)路由基本使用、工作模式(history,hash)、query传参和param传参、props配置、编程式路由导航
  • TypeScript概念讲解
  • C++ | Leetcode C++题解之第437题路径总和III
  • 回复《对话损友 2》
  • MySQL - 运维篇
  • WebGIS开发及市面上各种二三维GIS开发框架对比分析
  • [论文精读]TorWard: Discovery, Blocking, and Traceback of Malicious Traffic Over Tor
  • pytest - 多线程提速
  • python中logging的用法