using System; using System.IO; public enum LogLevel { Debug, Info, Warning, Error, Fatal } public class Logger { private string _logFilePath; private LogLevel _minLogLevel; public Logger(string logFilePath, LogLevel minLogLevel = LogLevel.Info) { _logFilePath = logFilePath; _minLogLevel = minLogLevel; } public void Log(LogLevel level, string message, Exception ex = null) { if (level < _minLogLevel) { return; } string logMessage = $"{DateTime.Now.ToString()} [{level}] - {message}"; if (ex != null) { logMessage += $"\r\n{ex.ToString()}"; } try { using (StreamWriter writer = File.AppendText(_logFilePath)) { writer.WriteLine(logMessage); } } catch (Exception ex) { Console.WriteLine($"Failed to write to log file: {ex.Message}"); } } public void Debug(string message, Exception ex = null) { Log(LogLevel.Debug, message, ex); } public void Info(string message, Exception ex = null) { Log(LogLevel.Info, message, ex); } public void Warning(string message, Exception ex = null) { Log(LogLevel.Warning, message, ex); } public void Error(string message, Exception ex = null) { Log(LogLevel.Error, message, ex); } public void Fatal(string message, Exception ex = null) { Log(LogLevel.Fatal, message, ex); } }
Logger logger = new Logger("C:\\mylog.txt"); logger.Debug("Debug message"); logger.Info("Info message"); logger.Warning("Warning message"); logger.Error("Error message", new Exception("Something went wrong")); logger.Fatal("Fatal message", new Exception("Something really went wrong"));标签:Exception,string,C#,message,LogLevel,ex,Logger,public From: https://www.cnblogs.com/vicky2021/p/17173819.html