C#轻量级日志功能(只有一个类)

最近在开发基于.net6的一个数据监控软件,使用其它开源log库都有点麻烦,就想着对Console.WriteLine()方法重定向到文件,非常方便的实现日志记录功能,同时也不影响之前的代码结构。

public class LogTextWriter : TextWriter
{
    public LogTextWriter()
    {
    }

    public override Encoding Encoding => Encoding.UTF8;

    public EventHandler<string> OnLogging;

    public override void Write(string? value)
    {
        string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        string path = GetPath();
        File.AppendAllText(path,$"{timestamp} - {value}");
    }

    public override void WriteLine(string? value)
    {
        if(value!=null)
        {
            OnLogging?.Invoke(this,value);
            string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string path = GetPath();
            File.AppendAllText(path, $"{timestamp} - {value}{Environment.NewLine}");
        }
    }

    private string GetPath()
    {
        if(!Directory.Exists("./log"))
        {
            Directory.CreateDirectory("./log");
        }
        // 获取当前日期和时间作为日志文件名的一部分
        string currentDateTime = DateTime.Now.ToString("yyyy_MM_dd");
        // 构建日志文件路径
        string logFilePath = $"log/log_{currentDateTime}.txt";
        return logFilePath;
    }

    private static LogTextWriter _instance = new LogTextWriter();
    public static LogTextWriter GetInstance()
    {
        return _instance;
    }
}

软件开始的地方要设置该重定向:

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    Console.SetOut(LogTextWriter.GetInstance());
    Console.WriteLine("程序启动成功!");
}

你可能感兴趣的:(c#,开发语言)