Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Использование
- * var logger = new Logger();
- * logger.Info("ХУЙ");
- * logger.Error("ПИЗДА");
- *
- */
- public class Logger
- {
- private const string FILE_EXT = ".log";
- private readonly object _fileLock = new();
- private readonly string _datetimeFormat;
- private readonly string _logFilename;
- [Flags]
- private enum LogLevel
- {
- INFO,
- ERROR
- }
- public Logger()
- {
- _datetimeFormat = "yyyy-MM-dd HH:mm:ss.fff"; //напр. 2024-07-09 12:54:25.738
- _logFilename = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + FILE_EXT; //папка debug
- string logHeader = _logFilename + " создан.";
- if (!File.Exists(_logFilename))
- {
- WriteLine(DateTime.Now.ToString(_datetimeFormat) + " " + logHeader);
- }
- }
- public void Error(string text)
- {
- WriteFormattedLog(LogLevel.ERROR, text);
- }
- public void Info(string text)
- {
- WriteFormattedLog(LogLevel.INFO, text);
- }
- private void WriteLine(string text)
- {
- if (string.IsNullOrEmpty(text)) return;
- lock (_fileLock)
- {
- using (StreamWriter writer = new StreamWriter(_logFilename, true, System.Text.Encoding.UTF8))
- {
- writer.WriteLine(text);
- }
- }
- }
- private void WriteFormattedLog(LogLevel level, string messageText)
- {
- string messageHeader = level switch
- {
- LogLevel.INFO => DateTime.Now.ToString(_datetimeFormat) + " [INFO] - ",
- LogLevel.ERROR => DateTime.Now.ToString(_datetimeFormat) + " [ERROR] - ",
- _ => "[UNDEFINED]"
- };
- WriteLine(messageHeader + messageText);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement