简单实现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;
}
}
}