Advertisement
anticlown

Simple logger class (C#)

Jul 9th, 2024
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.82 KB | None | 0 0
  1. /*
  2.  * Использование
  3.  * var logger = new Logger();
  4.  * logger.Info("ХУЙ");
  5.  * logger.Error("ПИЗДА");
  6.  *
  7.  */
  8.  
  9. public class Logger
  10. {
  11.     private const string FILE_EXT = ".log";
  12.     private readonly object _fileLock = new();
  13.     private readonly string _datetimeFormat;
  14.     private readonly string _logFilename;
  15.    
  16.     [Flags]
  17.     private enum LogLevel
  18.     {
  19.         INFO,
  20.         ERROR
  21.     }
  22.    
  23.     public Logger()
  24.     {
  25.         _datetimeFormat = "yyyy-MM-dd HH:mm:ss.fff"; //напр. 2024-07-09 12:54:25.738
  26.         _logFilename = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + FILE_EXT; //папка debug
  27.        
  28.         string logHeader = _logFilename + " создан.";
  29.         if (!File.Exists(_logFilename))
  30.         {
  31.             WriteLine(DateTime.Now.ToString(_datetimeFormat) + " " + logHeader);
  32.         }
  33.     }
  34.  
  35.     public void Error(string text)
  36.     {
  37.         WriteFormattedLog(LogLevel.ERROR, text);
  38.     }
  39.    
  40.     public void Info(string text)
  41.     {
  42.         WriteFormattedLog(LogLevel.INFO, text);
  43.     }
  44.  
  45.     private void WriteLine(string text)
  46.     {
  47.         if (string.IsNullOrEmpty(text)) return;
  48.        
  49.         lock (_fileLock)
  50.         {
  51.             using (StreamWriter writer = new StreamWriter(_logFilename, true, System.Text.Encoding.UTF8))
  52.             {
  53.                 writer.WriteLine(text);
  54.             }
  55.         }
  56.     }
  57.  
  58.     private void WriteFormattedLog(LogLevel level, string messageText)
  59.     {
  60.         string messageHeader = level switch
  61.         {
  62.             LogLevel.INFO => DateTime.Now.ToString(_datetimeFormat) + " [INFO] - ",
  63.             LogLevel.ERROR => DateTime.Now.ToString(_datetimeFormat) + " [ERROR] - ",
  64.             _ => "[UNDEFINED]"
  65.         };
  66.  
  67.         WriteLine(messageHeader + messageText);
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement