A simple Log singleton in C#
Here is a simple Log singleton in C#.
Updated: 7/25/2016
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | using System; using System.IO; namespace Rhyous.Logging { public class Log { #region Singleton private static readonly Lazy<Log> Lazy = new Lazy<Log>(() => new Log()); public static Log Instance { get { return Lazy.Value; } } internal Log() { LogFileName = "Example" ; LogFileExtension = ".log" ; } #endregion public StreamWriter Writer { get ; set ; } public string LogPath { get { return _LogPath ?? (_LogPath = AppDomain.CurrentDomain.BaseDirectory); } set { _LogPath = value; } } private string _LogPath; public string LogFileName { get ; set ; } public string LogFileExtension { get ; set ; } public string LogFile { get { return LogFileName + LogFileExtension; } } public string LogFullPath { get { return Path.Combine(LogPath, LogFile); } } public bool LogExists { get { return File.Exists(LogFullPath); } } public void WriteLineToLog( string inLogMessage) { WriteToLog(inLogMessage + Environment.NewLine); } public void WriteToLog( string inLogMessage) { if (!Directory.Exists(LogPath)) { Directory.CreateDirectory(LogPath); } if (Writer == null ) { Writer = new StreamWriter(LogFullPath, true ); } Writer.Write(inLogMessage); Writer.Flush(); } public static void WriteLine( string inLogMessage) { Instance.WriteLineToLog(inLogMessage); } public static void Write( string inLogMessage) { Instance.WriteToLog(inLogMessage); } } } |
Note: This is not tested with multiple threads as this is a simple example.