├── SimpleLogger ├── Logging │ ├── ILoggerHandler.cs │ ├── Formatters │ │ ├── ILoggerFormatter.cs │ │ └── DefaultLoggerFormatter.cs │ ├── Module │ │ ├── Database │ │ │ ├── DatabaseType.cs │ │ │ ├── DatabaseExtensions.cs │ │ │ └── DatabaseFactory.cs │ │ ├── LoggerModule.cs │ │ ├── ModuleManager.cs │ │ ├── DatabaseLoggerModule.cs │ │ └── EmailSenderLoggerModule.cs │ ├── ILoggerHandlerManager.cs │ ├── Handlers │ │ ├── ConsoleLoggerHandler.cs │ │ ├── DebugConsoleLoggerHandler.cs │ │ └── FileLoggerHandler.cs │ ├── DebugLogger.cs │ ├── LogMessage.cs │ └── LogPublisher.cs ├── packages.config ├── Properties │ └── AssemblyInfo.cs ├── app.config ├── SimpleLogger.csproj └── Logger.cs ├── SimpleLogger.Sample ├── App.config ├── Properties │ └── AssemblyInfo.cs ├── SimpleLogger.Sample.csproj └── Program.cs ├── .gitattributes ├── LICENSE ├── SimpleLogger.sln ├── README.md └── .gitignore /SimpleLogger/Logging/ILoggerHandler.cs: -------------------------------------------------------------------------------- 1 | namespace SimpleLogger.Logging 2 | { 3 | public interface ILoggerHandler 4 | { 5 | void Publish(LogMessage logMessage); 6 | } 7 | } -------------------------------------------------------------------------------- /SimpleLogger.Sample/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /SimpleLogger/Logging/Formatters/ILoggerFormatter.cs: -------------------------------------------------------------------------------- 1 | namespace SimpleLogger.Logging.Formatters 2 | { 3 | public interface ILoggerFormatter 4 | { 5 | string ApplyFormat(LogMessage logMessage); 6 | } 7 | } -------------------------------------------------------------------------------- /SimpleLogger/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /SimpleLogger/Logging/Module/Database/DatabaseType.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace SimpleLogger.Logging.Module.Database 7 | { 8 | public enum DatabaseType 9 | { 10 | MsSql = 1, 11 | Oracle = 2, // Only works on x64 machines 12 | MySql = 3 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /SimpleLogger/Logging/ILoggerHandlerManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace SimpleLogger.Logging 4 | { 5 | public interface ILoggerHandlerManager 6 | { 7 | ILoggerHandlerManager AddHandler(ILoggerHandler loggerHandler); 8 | ILoggerHandlerManager AddHandler(ILoggerHandler loggerHandler, Predicate filter); 9 | 10 | bool RemoveHandler(ILoggerHandler loggerHandler); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /SimpleLogger/Logging/Module/LoggerModule.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace SimpleLogger.Logging.Module 4 | { 5 | public abstract class LoggerModule 6 | { 7 | public abstract string Name { get; } 8 | public virtual void BeforeLog() { } 9 | public virtual void AfterLog(LogMessage logMessage) { } 10 | public virtual void ExceptionLog(Exception exception) { } 11 | public virtual void Initialize() { } 12 | } 13 | } -------------------------------------------------------------------------------- /SimpleLogger/Logging/Formatters/DefaultLoggerFormatter.cs: -------------------------------------------------------------------------------- 1 | namespace SimpleLogger.Logging.Formatters 2 | { 3 | internal class DefaultLoggerFormatter : ILoggerFormatter 4 | { 5 | public string ApplyFormat(LogMessage logMessage) 6 | { 7 | return string.Format("{0:dd.MM.yyyy HH:mm:ss}: {1} [line: {2} {3} -> {4}()]: {5}", 8 | logMessage.DateTime, logMessage.Level, logMessage.LineNumber, logMessage.CallingClass, 9 | logMessage.CallingMethod, logMessage.Text); 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | *.sln merge=union 7 | *.csproj merge=union 8 | *.vbproj merge=union 9 | *.fsproj merge=union 10 | *.dbproj merge=union 11 | 12 | # Standard to msysgit 13 | *.doc diff=astextplain 14 | *.DOC diff=astextplain 15 | *.docx diff=astextplain 16 | *.DOCX diff=astextplain 17 | *.dot diff=astextplain 18 | *.DOT diff=astextplain 19 | *.pdf diff=astextplain 20 | *.PDF diff=astextplain 21 | *.rtf diff=astextplain 22 | *.RTF diff=astextplain 23 | -------------------------------------------------------------------------------- /SimpleLogger/Logging/Handlers/ConsoleLoggerHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using SimpleLogger.Logging.Formatters; 3 | 4 | namespace SimpleLogger.Logging.Handlers 5 | { 6 | public class ConsoleLoggerHandler : ILoggerHandler 7 | { 8 | private readonly ILoggerFormatter _loggerFormatter; 9 | 10 | public ConsoleLoggerHandler() : this(new DefaultLoggerFormatter()) { } 11 | 12 | public ConsoleLoggerHandler(ILoggerFormatter loggerFormatter) 13 | { 14 | _loggerFormatter = loggerFormatter; 15 | } 16 | 17 | public void Publish(LogMessage logMessage) 18 | { 19 | Console.WriteLine(_loggerFormatter.ApplyFormat(logMessage)); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /SimpleLogger/Logging/Handlers/DebugConsoleLoggerHandler.cs: -------------------------------------------------------------------------------- 1 | using SimpleLogger.Logging.Formatters; 2 | 3 | namespace SimpleLogger.Logging.Handlers 4 | { 5 | public class DebugConsoleLoggerHandler : ILoggerHandler 6 | { 7 | private readonly ILoggerFormatter _loggerFormatter; 8 | 9 | public DebugConsoleLoggerHandler() : this(new DefaultLoggerFormatter()) { } 10 | 11 | public DebugConsoleLoggerHandler(ILoggerFormatter loggerFormatter) 12 | { 13 | _loggerFormatter = loggerFormatter; 14 | } 15 | 16 | public void Publish(LogMessage logMessage) 17 | { 18 | System.Diagnostics.Debug.WriteLine(_loggerFormatter.ApplyFormat(logMessage)); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /SimpleLogger/Logging/Module/Database/DatabaseExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data; 4 | using System.Linq; 5 | using System.Text; 6 | 7 | namespace SimpleLogger.Logging.Module.Database 8 | { 9 | internal static class DatabaseExtensions 10 | { 11 | internal static void ExecuteMultipleNonQuery(this IDbCommand dbCommand) 12 | { 13 | var sqlStatementArray = dbCommand.CommandText 14 | .Split(new string[] { ";" }, 15 | StringSplitOptions.RemoveEmptyEntries); 16 | 17 | foreach (string sqlStatement in sqlStatementArray) 18 | { 19 | dbCommand.CommandText = sqlStatement; 20 | dbCommand.ExecuteNonQuery(); 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /SimpleLogger/Logging/DebugLogger.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace SimpleLogger.Logging 4 | { 5 | public class DebugLogger 6 | { 7 | private const Logger.Level DebugLevel = Logger.Level.Debug; 8 | 9 | public void Log() 10 | { 11 | Log("There is no message"); 12 | } 13 | 14 | public void Log(string message) 15 | { 16 | Logger.Log(DebugLevel, message); 17 | } 18 | 19 | public void Log(Exception exception) 20 | { 21 | Logger.Log(DebugLevel, exception.Message); 22 | } 23 | 24 | public void Log(Exception exception) where TClass : class 25 | { 26 | var message = string.Format("Log exception -> Message: {0}\nStackTrace: {1}", exception.Message, exception.StackTrace); 27 | Logger.Log(DebugLevel, message); 28 | } 29 | 30 | public void Log(string message) where TClass : class 31 | { 32 | Logger.Log(DebugLevel, message); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /SimpleLogger/Logging/LogMessage.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using SimpleLogger.Logging.Formatters; 3 | 4 | namespace SimpleLogger.Logging 5 | { 6 | public class LogMessage 7 | { 8 | public DateTime DateTime { get; set; } 9 | public Logger.Level Level { get; set; } 10 | public string Text { get; set; } 11 | public string CallingClass { get; set; } 12 | public string CallingMethod { get; set; } 13 | public int LineNumber { get; set; } 14 | 15 | public LogMessage() { } 16 | 17 | public LogMessage(Logger.Level level, string text, DateTime dateTime, string callingClass, string callingMethod, int lineNumber) 18 | { 19 | Level = level; 20 | Text = text; 21 | DateTime = dateTime; 22 | CallingClass = callingClass; 23 | CallingMethod = callingMethod; 24 | LineNumber = lineNumber; 25 | } 26 | 27 | public override string ToString() 28 | { 29 | return new DefaultLoggerFormatter().ApplyFormat(this); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 jirkapenzes 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /SimpleLogger.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2012 4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleLogger", "SimpleLogger\SimpleLogger.csproj", "{CF8C9230-CC66-43DF-8070-01EB53978B5E}" 5 | EndProject 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleLogger.Sample", "SimpleLogger.Sample\SimpleLogger.Sample.csproj", "{B549C21C-831A-44A4-9FC4-E0379E2A562D}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {CF8C9230-CC66-43DF-8070-01EB53978B5E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {CF8C9230-CC66-43DF-8070-01EB53978B5E}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {CF8C9230-CC66-43DF-8070-01EB53978B5E}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {CF8C9230-CC66-43DF-8070-01EB53978B5E}.Release|Any CPU.Build.0 = Release|Any CPU 18 | {B549C21C-831A-44A4-9FC4-E0379E2A562D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {B549C21C-831A-44A4-9FC4-E0379E2A562D}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {B549C21C-831A-44A4-9FC4-E0379E2A562D}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {B549C21C-831A-44A4-9FC4-E0379E2A562D}.Release|Any CPU.Build.0 = Release|Any CPU 22 | EndGlobalSection 23 | GlobalSection(SolutionProperties) = preSolution 24 | HideSolutionNode = FALSE 25 | EndGlobalSection 26 | EndGlobal 27 | -------------------------------------------------------------------------------- /SimpleLogger/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("SimpleLogger")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("SimpleLogger")] 13 | [assembly: AssemblyCopyright("Copyright © 2012")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("1fb22d50-4d20-494e-8ac5-d18455db2bb7")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /SimpleLogger.Sample/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("SimpleLogger.Sample")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("SimpleLogger.Sample")] 13 | [assembly: AssemblyCopyright("Copyright © 2012")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("c6968a0e-3d81-41bb-a357-eb62aaec3e94")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /SimpleLogger/Logging/Module/ModuleManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace SimpleLogger.Logging.Module 7 | { 8 | public class ModuleManager 9 | { 10 | private readonly IDictionary _modules; 11 | 12 | public ModuleManager() 13 | { 14 | _modules = new Dictionary(); 15 | } 16 | 17 | public void BeforeLog() 18 | { 19 | foreach (var loggerModule in _modules.Values) 20 | loggerModule.BeforeLog(); 21 | } 22 | 23 | public void AfterLog(LogMessage logMessage) 24 | { 25 | foreach (var loggerModule in _modules.Values) 26 | loggerModule.AfterLog(logMessage); 27 | } 28 | 29 | public void ExceptionLog(Exception exception) 30 | { 31 | foreach (var loggerModule in _modules.Values) 32 | loggerModule.ExceptionLog(exception); 33 | } 34 | 35 | public void Install(LoggerModule module) 36 | { 37 | if (!_modules.ContainsKey(module.Name)) 38 | { 39 | module.Initialize(); 40 | _modules.Add(module.Name, module); 41 | } 42 | else 43 | { 44 | // reinstall module 45 | Uninstall(module.Name); 46 | Install(module); 47 | } 48 | } 49 | 50 | public void Uninstall(LoggerModule module) 51 | { 52 | if (_modules.ContainsKey(module.Name)) 53 | _modules.Remove(module.Name); 54 | } 55 | 56 | public void Uninstall(string moduleName) 57 | { 58 | if (_modules.ContainsKey(moduleName)) 59 | _modules.Remove(moduleName); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /SimpleLogger/app.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |
6 | 7 | 8 | 9 | 10 | 12 | 13 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /SimpleLogger/Logging/Handlers/FileLoggerHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using SimpleLogger.Logging.Formatters; 4 | 5 | namespace SimpleLogger.Logging.Handlers 6 | { 7 | public class FileLoggerHandler : ILoggerHandler 8 | { 9 | private readonly string _fileName; 10 | private readonly string _directory; 11 | private readonly ILoggerFormatter _loggerFormatter; 12 | 13 | public FileLoggerHandler() : this(CreateFileName()) { } 14 | 15 | public FileLoggerHandler(string fileName) : this(fileName, string.Empty) { } 16 | 17 | public FileLoggerHandler(string fileName, string directory) : this(new DefaultLoggerFormatter(), fileName, directory) { } 18 | 19 | public FileLoggerHandler(ILoggerFormatter loggerFormatter) : this(loggerFormatter, CreateFileName()) { } 20 | 21 | public FileLoggerHandler(ILoggerFormatter loggerFormatter, string fileName) : this(loggerFormatter, fileName, string.Empty) { } 22 | 23 | public FileLoggerHandler(ILoggerFormatter loggerFormatter, string fileName, string directory) 24 | { 25 | _loggerFormatter = loggerFormatter; 26 | _fileName = fileName; 27 | _directory = directory; 28 | } 29 | 30 | public void Publish(LogMessage logMessage) 31 | { 32 | if (!string.IsNullOrEmpty(_directory)) 33 | { 34 | var directoryInfo = new DirectoryInfo(Path.Combine(_directory)); 35 | if (!directoryInfo.Exists) 36 | directoryInfo.Create(); 37 | } 38 | 39 | using (var writer = new StreamWriter(File.Open(Path.Combine(_directory, _fileName), FileMode.Append))) 40 | writer.WriteLine(_loggerFormatter.ApplyFormat(logMessage)); 41 | } 42 | 43 | private static string CreateFileName() 44 | { 45 | var currentDate = DateTime.Now; 46 | var guid = Guid.NewGuid(); 47 | return string.Format("Log_{0:0000}{1:00}{2:00}-{3:00}{4:00}_{5}.log", 48 | currentDate.Year, currentDate.Month, currentDate.Day, currentDate.Hour, currentDate.Minute, guid); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /SimpleLogger/Logging/LogPublisher.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace SimpleLogger.Logging 5 | { 6 | internal class FilteredHandler : ILoggerHandler 7 | { 8 | public Predicate Filter { get; set; } 9 | public ILoggerHandler Handler { get; set; } 10 | 11 | public void Publish(LogMessage logMessage) 12 | { 13 | if (Filter(logMessage)) 14 | Handler.Publish (logMessage); 15 | } 16 | } 17 | 18 | internal class LogPublisher : ILoggerHandlerManager 19 | { 20 | private readonly IList _loggerHandlers; 21 | private readonly IList _messages; 22 | 23 | public LogPublisher() 24 | { 25 | _loggerHandlers = new List(); 26 | _messages = new List(); 27 | StoreLogMessages = false; 28 | } 29 | 30 | public LogPublisher(bool storeLogMessages) 31 | { 32 | _loggerHandlers = new List(); 33 | _messages = new List(); 34 | StoreLogMessages = storeLogMessages; 35 | } 36 | 37 | public void Publish(LogMessage logMessage) 38 | { 39 | if (StoreLogMessages) 40 | _messages.Add(logMessage); 41 | foreach (var loggerHandler in _loggerHandlers) 42 | loggerHandler.Publish(logMessage); 43 | } 44 | 45 | public ILoggerHandlerManager AddHandler(ILoggerHandler loggerHandler) 46 | { 47 | if (loggerHandler != null) 48 | _loggerHandlers.Add(loggerHandler); 49 | return this; 50 | } 51 | 52 | public ILoggerHandlerManager AddHandler(ILoggerHandler loggerHandler, Predicate filter) 53 | { 54 | if ((filter == null) || loggerHandler == null) 55 | return this; 56 | 57 | return AddHandler(new FilteredHandler() { 58 | Filter = filter, 59 | Handler = loggerHandler 60 | }); 61 | } 62 | 63 | public bool RemoveHandler(ILoggerHandler loggerHandler) 64 | { 65 | return _loggerHandlers.Remove(loggerHandler); 66 | } 67 | 68 | public IEnumerable Messages 69 | { 70 | get { return _messages; } 71 | } 72 | 73 | /// 74 | /// Gets or sets a value indicating whether this store log messages. 75 | /// 76 | /// true if store log messages; otherwise, false. By default is false 77 | public bool StoreLogMessages { get; set; } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /SimpleLogger.Sample/SimpleLogger.Sample.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {B549C21C-831A-44A4-9FC4-E0379E2A562D} 8 | Exe 9 | Properties 10 | SimpleLogger.Sample 11 | SimpleLogger.Sample 12 | v4.0 13 | 512 14 | 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | {CF8C9230-CC66-43DF-8070-01EB53978B5E} 54 | SimpleLogger 55 | 56 | 57 | 58 | 65 | -------------------------------------------------------------------------------- /SimpleLogger/Logging/Module/DatabaseLoggerModule.cs: -------------------------------------------------------------------------------- 1 | using SimpleLogger.Logging.Module.Database; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Data; 5 | using System.Data.Common; 6 | using System.Linq; 7 | using System.Text; 8 | 9 | namespace SimpleLogger.Logging.Module 10 | { 11 | public class DatabaseLoggerModule : LoggerModule 12 | { 13 | private readonly string _connectionString; 14 | private readonly string _tableName; 15 | private readonly DatabaseType _databaseType; 16 | 17 | public DatabaseLoggerModule(DatabaseType databaseType, string connectionString) 18 | : this(databaseType, connectionString, "Log") { } 19 | 20 | public DatabaseLoggerModule(DatabaseType databaseType, string connectionString, string tableName) 21 | { 22 | _databaseType = databaseType; 23 | _connectionString = connectionString; 24 | _tableName = tableName; 25 | } 26 | 27 | public override void Initialize() 28 | { 29 | CreateTable(); 30 | } 31 | 32 | public override string Name 33 | { 34 | get { return DatabaseFactory.GetDatabaseName(_databaseType); } 35 | } 36 | 37 | private DbParameter GetParameter(DbCommand command, string name, object value, DbType type) 38 | { 39 | var parameter = command.CreateParameter(); 40 | parameter.DbType = type; 41 | parameter.ParameterName = (_databaseType.Equals(DatabaseType.Oracle) ? ":" : "@") + name; 42 | parameter.Value = value; 43 | return parameter; 44 | } 45 | 46 | private void AddParameter(DbCommand command, string name, object value, DbType type) 47 | { 48 | command.Parameters.Add(GetParameter(command, name, value, type)); 49 | } 50 | 51 | public override void AfterLog(LogMessage logMessage) 52 | { 53 | using (var connection = DatabaseFactory.GetConnection(_databaseType, _connectionString)) 54 | { 55 | connection.Open(); 56 | var commandText = DatabaseFactory.GetInsertCommand(_databaseType, _tableName); 57 | var sqlCommand = DatabaseFactory.GetCommand(_databaseType, commandText, connection); 58 | 59 | AddParameter(sqlCommand, "text", logMessage.Text, DbType.String); 60 | AddParameter(sqlCommand, "dateTime", logMessage.DateTime, DbType.Date); 61 | AddParameter(sqlCommand, "log_level", logMessage.Level.ToString(), DbType.String); 62 | AddParameter(sqlCommand, "callingClass", logMessage.CallingClass, DbType.String); 63 | AddParameter(sqlCommand, "callingMethod", logMessage.CallingMethod, DbType.String); 64 | 65 | sqlCommand.ExecuteNonQuery(); 66 | } 67 | } 68 | 69 | private void CreateTable() 70 | { 71 | var connection = DatabaseFactory.GetConnection(_databaseType, _connectionString); 72 | 73 | using (connection) 74 | { 75 | connection.Open(); 76 | var sqlCommand = DatabaseFactory.GetCommand 77 | ( 78 | _databaseType, 79 | DatabaseFactory.GetCheckIfShouldCreateTableQuery(_databaseType), 80 | connection 81 | ); 82 | 83 | AddParameter(sqlCommand, "tableName", _tableName.ToLower(), DbType.String); 84 | 85 | var result = sqlCommand.ExecuteScalar(); 86 | 87 | if (result == null) 88 | { 89 | var commandText = string.Format(DatabaseFactory.GetCreateTableQuery(_databaseType), _tableName); 90 | sqlCommand = DatabaseFactory.GetCommand(_databaseType, commandText, connection); 91 | sqlCommand.ExecuteMultipleNonQuery(); 92 | } 93 | } 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /SimpleLogger/Logging/Module/EmailSenderLoggerModule.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net; 4 | using System.Net.Mail; 5 | using System.Text; 6 | using SimpleLogger.Logging.Formatters; 7 | 8 | namespace SimpleLogger.Logging.Module 9 | { 10 | public class EmailSenderLoggerModule : LoggerModule 11 | { 12 | private readonly SmtpServerConfiguration _smtpServerConfiguration; 13 | 14 | public string Sender { get; set; } 15 | public IList Recipients { get; private set; } 16 | public bool EnableSsl { get; set; } 17 | 18 | private readonly string _subject; 19 | private readonly ILoggerFormatter _loggerFormatter; 20 | 21 | public EmailSenderLoggerModule(SmtpServerConfiguration smtpServerConfiguration) 22 | : this(smtpServerConfiguration, GenerateSubjectName()) { } 23 | 24 | public EmailSenderLoggerModule(SmtpServerConfiguration smtpServerConfiguration, string subject) 25 | : this(smtpServerConfiguration, subject, new DefaultLoggerFormatter()) { } 26 | 27 | public EmailSenderLoggerModule(SmtpServerConfiguration smtpServerConfiguration, ILoggerFormatter loggerFormatter) 28 | : this(smtpServerConfiguration, GenerateSubjectName(), loggerFormatter) { } 29 | 30 | public EmailSenderLoggerModule(SmtpServerConfiguration smtpServerConfiguration, string subject, ILoggerFormatter loggerFormatter) 31 | { 32 | _smtpServerConfiguration = smtpServerConfiguration; 33 | _subject = subject; 34 | _loggerFormatter = loggerFormatter; 35 | 36 | Recipients = new List(); 37 | } 38 | 39 | public override string Name 40 | { 41 | get { return "EmailSenderLoggerModule"; } 42 | } 43 | 44 | public override void ExceptionLog(Exception exception) 45 | { 46 | if (string.IsNullOrEmpty(Sender) || Recipients.Count == 0) 47 | throw new NullReferenceException("Not specified email sender and recipient. "); 48 | 49 | var body = MakeEmailBodyFromLogHistory(); 50 | var client = new SmtpClient(_smtpServerConfiguration.Host, _smtpServerConfiguration.Port) 51 | { 52 | EnableSsl = EnableSsl, 53 | UseDefaultCredentials = false, 54 | Credentials = new NetworkCredential(_smtpServerConfiguration.UserName, _smtpServerConfiguration.Password) 55 | }; 56 | 57 | foreach (var recipient in Recipients) 58 | { 59 | using (var mailMessage = new MailMessage(Sender, recipient, _subject, body)) 60 | { 61 | client.Send(mailMessage); 62 | } 63 | } 64 | } 65 | 66 | private static string GenerateSubjectName() 67 | { 68 | var currentDate = DateTime.Now; 69 | return string.Format("SimpleLogger {0} {1}", currentDate.ToShortDateString(), currentDate.ToShortTimeString()); 70 | } 71 | 72 | private string MakeEmailBodyFromLogHistory() 73 | { 74 | var stringBuilder = new StringBuilder(); 75 | stringBuilder.AppendLine("Simple logger - email module"); 76 | 77 | foreach (var logMessage in Logger.Messages) 78 | stringBuilder.AppendLine(_loggerFormatter.ApplyFormat(logMessage)); 79 | 80 | return stringBuilder.ToString(); 81 | } 82 | } 83 | 84 | public class SmtpServerConfiguration 85 | { 86 | public string UserName { get; private set; } 87 | public string Password { get; private set; } 88 | public string Host { get; private set; } 89 | public int Port { get; private set; } 90 | 91 | public SmtpServerConfiguration(string userName, string password, string host, int port) 92 | { 93 | UserName = userName; 94 | Password = password; 95 | Host = host; 96 | Port = port; 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /SimpleLogger/SimpleLogger.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {CF8C9230-CC66-43DF-8070-01EB53978B5E} 8 | Library 9 | Properties 10 | SimpleLogger 11 | SimpleLogger 12 | v4.0 13 | 512 14 | 15 | 16 | 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | pdbonly 27 | true 28 | bin\Release\ 29 | TRACE 30 | prompt 31 | 4 32 | 33 | 34 | 35 | False 36 | ..\packages\MySql.Data.6.9.8\lib\net40\MySql.Data.dll 37 | 38 | 39 | False 40 | ..\packages\Oracle.ManagedDataAccess.12.1.2400\lib\net40\Oracle.ManagedDataAccess.dll 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 | 72 | 73 | 74 | 75 | 76 | 83 | -------------------------------------------------------------------------------- /SimpleLogger.Sample/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using SimpleLogger.Logging.Handlers; 3 | using SimpleLogger.Logging.Module; 4 | using SimpleLogger.Logging.Module.Database; 5 | 6 | namespace SimpleLogger.Sample 7 | { 8 | class Program 9 | { 10 | public static void Main() 11 | { 12 | // Adding handler - to show log messages (ILoggerHandler) 13 | Logger.LoggerHandlerManager 14 | .AddHandler(new ConsoleLoggerHandler()) 15 | .AddHandler(new FileLoggerHandler()) 16 | .AddHandler(new DebugConsoleLoggerHandler()); 17 | 18 | // Fast logging (monitor name of class and methods from which is the application logged) 19 | Logger.Log(); 20 | 21 | // We define a log message 22 | Logger.Log("Hello world"); 23 | 24 | // We can define the level (type) of message 25 | Logger.Log(Logger.Level.Fine, "Explicit define level"); 26 | 27 | // Explicit definition of the class from which the logging 28 | Logger.Log("Explicit define log class"); 29 | Logger.Log(Logger.Level.Fine, "Explicit define log class and level"); 30 | 31 | // Settings of default type of message 32 | Logger.DefaultLevel = Logger.Level.Severe; 33 | 34 | try 35 | { 36 | // Simulation of exceptions 37 | throw new Exception(); 38 | } 39 | catch (Exception exception) 40 | { 41 | // Logging exceptions 42 | // Automatical adjustment of specific log into the Error and adding of StackTrace 43 | Logger.Log(exception); 44 | Logger.Log(exception); 45 | } 46 | 47 | // Special feature - debug logging 48 | 49 | Logger.Debug.Log("Debug log"); 50 | Logger.Debug.Log("Debug log"); 51 | 52 | Logger.DebugOff(); 53 | Logger.Debug.Log("Not-logged message"); 54 | 55 | Logger.DebugOn(); 56 | Logger.Debug.Log("I'am back!"); 57 | 58 | Console.ReadKey(); 59 | } 60 | 61 | private static void MySqlDatabaseLoggerModuleSample() 62 | { 63 | // Just add the module and it works! 64 | Logger.Modules.Install(new DatabaseLoggerModule(DatabaseType.MySql, "Your connection string here!")); 65 | Logger.Log("My first database log! "); 66 | } 67 | 68 | private static void MsSqlDatabaseLoggerModuleSample() 69 | { 70 | // Just add the module and it works! 71 | Logger.Modules.Install(new DatabaseLoggerModule(DatabaseType.MsSql, "Your connection string here!")); 72 | Logger.Log("My first database log! "); 73 | } 74 | 75 | private static void OracleDatabaseLoggerModuleSample() 76 | { 77 | // Just add the module and it works! 78 | Logger.Modules.Install(new DatabaseLoggerModule(DatabaseType.Oracle, "Your connection string here!")); 79 | Logger.Log("My first database log! "); 80 | } 81 | 82 | public static void EmailModuleSample() 83 | { 84 | // Configuring smtp server 85 | var smtpServerConfiguration = new SmtpServerConfiguration("userName", "password", "smtp.gmail.com", 587); 86 | 87 | // Creating a module 88 | var emailSenderLoggerModule = new EmailSenderLoggerModule(smtpServerConfiguration) 89 | { 90 | EnableSsl = true, 91 | Sender = "sender-email@gmail.com" 92 | }; 93 | 94 | // Add the module and it works 95 | emailSenderLoggerModule.Recipients.Add("recipients@gmail.com"); 96 | 97 | // // Simulation of exceptions 98 | Logger.Modules.Install(emailSenderLoggerModule); 99 | 100 | try 101 | { 102 | // Simulation of exceptions 103 | throw new NullReferenceException(); 104 | } 105 | catch (Exception exception) 106 | { 107 | // Log exception 108 | // If you catch an exception error -> will be sent an email with a list of log message. 109 | Logger.Log(exception); 110 | } 111 | } 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Simple Logger C#.NET 2 | ============= 3 | 4 | Very easy to use. 5 | 6 | Usage 7 | ------- 8 | ```csharp 9 | public static void Main() 10 | { 11 | // Adding handler - to show log messages (ILoggerHandler) 12 | Logger.LoggerHandlerManager 13 | .AddHandler(new ConsoleLoggerHandler()) 14 | .AddHandler(new FileLoggerHandler()) 15 | .AddHandler(new DebugConsoleLoggerHandler()); 16 | 17 | // Fast logging (monitor name of class and methods from which is the application logged) 18 | Logger.Log(); 19 | 20 | // We define a log message 21 | Logger.Log("Hello world"); 22 | 23 | // We can define the level (type) of message 24 | Logger.Log(Logger.Level.Fine, "Explicit define level"); 25 | 26 | // Explicit definition of the class from which the logging 27 | Logger.Log("Explicit define log class"); 28 | Logger.Log(Logger.Level.Fine, "Explicit define log class and level"); 29 | 30 | // Settings of default type of message 31 | Logger.DefaultLevel = Logger.Level.Severe; 32 | 33 | try 34 | { 35 | // Simulation of exceptions 36 | throw new Exception(); 37 | } 38 | catch (Exception exception) 39 | { 40 | // Logging exceptions 41 | // Automatical adjustment of specific log into the Error and adding of StackTrace 42 | Logger.Log(exception); 43 | Logger.Log(exception); 44 | } 45 | 46 | // Special feature - debug logging 47 | 48 | Logger.Debug.Log("Debug log"); 49 | Logger.Debug.Log("Debug log"); 50 | 51 | Logger.DebugOff(); 52 | Logger.Debug.Log("Not-logged message"); 53 | 54 | Logger.DebugOn(); 55 | Logger.Debug.Log("I'am back!"); 56 | 57 | Console.ReadKey(); 58 | } 59 | ``` 60 | 61 | #### Output 62 | ``` 63 | 12.10.2012 21:43: Info [line: 18 Program -> Main()]: There is no message 64 | 12.10.2012 21:43: Info [line: 21 Program -> Main()]: Hello world 65 | 12.10.2012 21:43: Fine [line: 24 Program -> Main()]: Explicit define level 66 | 12.10.2012 21:43: Info [line: 27 Program -> Main()]: Explicit define log class 67 | 12.10.2012 21:43: Fine [line: 28 Program -> Main()]: Explicit define log class and level 68 | 12.10.2012 21:43: Error [line: 35 Program -> Main()]: Exception of type 'System.Exception' was thrown. 69 | 12.10.2012 21:43: Error [line: 35 Program -> Main()]: Log exception -> Message: Exception of type 'System.Exception' was thrown. 70 | StackTrace: at SimpleLogger.Sample.Program.Main() in c:\GitHub\SimpleLogger\SimpleLogger.Sample\Program.cs:line 35 71 | 72 | 12.10.2012 21:43: Debug [line: 47 Program -> Main()]: Debug log 73 | 12.10.2012 21:43: Debug [line: 48 Program -> Main()]: Debug log 74 | 12.10.2012 21:43: Debug [line: 55 Program -> Main()]: I'am back! 75 | 76 | ``` 77 | 78 | 79 | Modules 80 | ------- 81 | ### Email module 82 | 83 | ```csharp 84 | // Email module sample 85 | public static void EmaiLModuleSample() 86 | { 87 | // Configuring smtp server 88 | var smtpServerConfiguration = new SmtpServerConfiguration("userName", "password", "smtp.gmail.com", 587); 89 | 90 | // Creating a module 91 | var emailSenderLoggerModule = new EmailSenderLoggerModule(smtpServerConfiguration) 92 | { 93 | EnableSsl = true, 94 | Sender = "sender-email@gmail.com" 95 | }; 96 | 97 | // Adding recipients 98 | emailSenderLoggerModule.Recipients.Add("recipients@gmail.com"); 99 | 100 | // Add the module and it works 101 | Logger.Modules.Install(emailSenderLoggerModule); 102 | 103 | try 104 | { 105 | // Simulation of exceptions 106 | throw new NullReferenceException(); 107 | } 108 | catch (Exception exception) 109 | { 110 | // Log exception 111 | // If you catch an exception error -> will be sent an email with a list of log message. 112 | Logger.Log(exception); 113 | } 114 | } 115 | ``` 116 | 117 | ### MS SQL database module 118 | ```csharp 119 | // MS SQL database module sample 120 | public static void MsSqlDatabaseLoggerModuleSample() 121 | { 122 | var connectionString = "Your connection string"; 123 | 124 | // Just add the module and it works! 125 | Logger.Modules.Install(new MsSqlDatabaseLoggerModule(connectionString)); 126 | Logger.Log("My first database log! "); 127 | } 128 | ``` -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | artifacts/ 46 | 47 | *_i.c 48 | *_p.c 49 | *_i.h 50 | *.ilk 51 | *.meta 52 | *.obj 53 | *.pch 54 | *.pdb 55 | *.pgc 56 | *.pgd 57 | *.rsp 58 | *.sbr 59 | *.tlb 60 | *.tli 61 | *.tlh 62 | *.tmp 63 | *.tmp_proj 64 | *.log 65 | *.vspscc 66 | *.vssscc 67 | .builds 68 | *.pidb 69 | *.svclog 70 | *.scc 71 | 72 | # Chutzpah Test files 73 | _Chutzpah* 74 | 75 | # Visual C++ cache files 76 | ipch/ 77 | *.aps 78 | *.ncb 79 | *.opendb 80 | *.opensdf 81 | *.sdf 82 | *.cachefile 83 | *.VC.db 84 | *.VC.VC.opendb 85 | 86 | # Visual Studio profiler 87 | *.psess 88 | *.vsp 89 | *.vspx 90 | *.sap 91 | 92 | # TFS 2012 Local Workspace 93 | $tf/ 94 | 95 | # Guidance Automation Toolkit 96 | *.gpState 97 | 98 | # ReSharper is a .NET coding add-in 99 | _ReSharper*/ 100 | *.[Rr]e[Ss]harper 101 | *.DotSettings.user 102 | 103 | # JustCode is a .NET coding add-in 104 | .JustCode 105 | 106 | # TeamCity is a build add-in 107 | _TeamCity* 108 | 109 | # DotCover is a Code Coverage Tool 110 | *.dotCover 111 | 112 | # NCrunch 113 | _NCrunch_* 114 | .*crunch*.local.xml 115 | nCrunchTemp_* 116 | 117 | # MightyMoose 118 | *.mm.* 119 | AutoTest.Net/ 120 | 121 | # Web workbench (sass) 122 | .sass-cache/ 123 | 124 | # Installshield output folder 125 | [Ee]xpress/ 126 | 127 | # DocProject is a documentation generator add-in 128 | DocProject/buildhelp/ 129 | DocProject/Help/*.HxT 130 | DocProject/Help/*.HxC 131 | DocProject/Help/*.hhc 132 | DocProject/Help/*.hhk 133 | DocProject/Help/*.hhp 134 | DocProject/Help/Html2 135 | DocProject/Help/html 136 | 137 | # Click-Once directory 138 | publish/ 139 | 140 | # Publish Web Output 141 | *.[Pp]ublish.xml 142 | *.azurePubxml 143 | # TODO: Comment the next line if you want to checkin your web deploy settings 144 | # but database connection strings (with potential passwords) will be unencrypted 145 | *.pubxml 146 | *.publishproj 147 | 148 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 149 | # checkin your Azure Web App publish settings, but sensitive information contained 150 | # in these scripts will be unencrypted 151 | PublishScripts/ 152 | 153 | # NuGet Packages 154 | *.nupkg 155 | # The packages folder can be ignored because of Package Restore 156 | **/packages/* 157 | # except build/, which is used as an MSBuild target. 158 | !**/packages/build/ 159 | # Uncomment if necessary however generally it will be regenerated when needed 160 | #!**/packages/repositories.config 161 | # NuGet v3's project.json files produces more ignoreable files 162 | *.nuget.props 163 | *.nuget.targets 164 | 165 | # Microsoft Azure Build Output 166 | csx/ 167 | *.build.csdef 168 | 169 | # Microsoft Azure Emulator 170 | ecf/ 171 | rcf/ 172 | 173 | # Windows Store app package directories and files 174 | AppPackages/ 175 | BundleArtifacts/ 176 | Package.StoreAssociation.xml 177 | _pkginfo.txt 178 | 179 | # Visual Studio cache files 180 | # files ending in .cache can be ignored 181 | *.[Cc]ache 182 | # but keep track of directories ending in .cache 183 | !*.[Cc]ache/ 184 | 185 | # Others 186 | ClientBin/ 187 | ~$* 188 | *~ 189 | *.dbmdl 190 | *.dbproj.schemaview 191 | *.pfx 192 | *.publishsettings 193 | node_modules/ 194 | orleans.codegen.cs 195 | 196 | # Since there are multiple workflows, uncomment next line to ignore bower_components 197 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 198 | #bower_components/ 199 | 200 | # RIA/Silverlight projects 201 | Generated_Code/ 202 | 203 | # Backup & report files from converting an old project file 204 | # to a newer Visual Studio version. Backup files are not needed, 205 | # because we have git ;-) 206 | _UpgradeReport_Files/ 207 | Backup*/ 208 | UpgradeLog*.XML 209 | UpgradeLog*.htm 210 | 211 | # SQL Server files 212 | *.mdf 213 | *.ldf 214 | 215 | # Business Intelligence projects 216 | *.rdl.data 217 | *.bim.layout 218 | *.bim_*.settings 219 | 220 | # Microsoft Fakes 221 | FakesAssemblies/ 222 | 223 | # GhostDoc plugin setting file 224 | *.GhostDoc.xml 225 | 226 | # Node.js Tools for Visual Studio 227 | .ntvs_analysis.dat 228 | 229 | # Visual Studio 6 build log 230 | *.plg 231 | 232 | # Visual Studio 6 workspace options file 233 | *.opt 234 | 235 | # Visual Studio LightSwitch build output 236 | **/*.HTMLClient/GeneratedArtifacts 237 | **/*.DesktopClient/GeneratedArtifacts 238 | **/*.DesktopClient/ModelManifest.xml 239 | **/*.Server/GeneratedArtifacts 240 | **/*.Server/ModelManifest.xml 241 | _Pvt_Extensions 242 | 243 | # Paket dependency manager 244 | .paket/paket.exe 245 | paket-files/ 246 | 247 | # FAKE - F# Make 248 | .fake/ 249 | 250 | # JetBrains Rider 251 | .idea/ 252 | *.sln.iml -------------------------------------------------------------------------------- /SimpleLogger/Logging/Module/Database/DatabaseFactory.cs: -------------------------------------------------------------------------------- 1 | using MySql.Data.MySqlClient; 2 | using Oracle.ManagedDataAccess.Client; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Data.Common; 6 | using System.Data.SqlClient; 7 | using System.Linq; 8 | using System.Text; 9 | 10 | namespace SimpleLogger.Logging.Module.Database 11 | { 12 | internal static class DatabaseFactory 13 | { 14 | internal static DbConnection GetConnection(DatabaseType databaseType, string connectionString) 15 | { 16 | switch (databaseType) 17 | { 18 | case DatabaseType.MsSql: 19 | return new SqlConnection(connectionString); 20 | case DatabaseType.Oracle: 21 | return new OracleConnection(connectionString); 22 | case DatabaseType.MySql: 23 | return new MySqlConnection(connectionString); 24 | } 25 | 26 | return null; 27 | } 28 | 29 | internal static DbCommand GetCommand(DatabaseType databaseType, string commandText, DbConnection connection) 30 | { 31 | switch (databaseType) 32 | { 33 | case DatabaseType.MsSql: 34 | return new SqlCommand(commandText, connection as SqlConnection); 35 | case DatabaseType.Oracle: 36 | return new OracleCommand(commandText, connection as OracleConnection) { BindByName = true }; 37 | case DatabaseType.MySql: 38 | return new MySqlCommand(commandText, connection as MySqlConnection); 39 | } 40 | 41 | return null; 42 | } 43 | 44 | internal static string GetDatabaseName(DatabaseType databaseType) 45 | { 46 | switch (databaseType) 47 | { 48 | case DatabaseType.MsSql: 49 | return "MsSqlDatabaseLoggerModule"; 50 | case DatabaseType.Oracle: 51 | return "OracleDatabaseLoggerModule"; 52 | case DatabaseType.MySql: 53 | return "MySqlDatabaseLoggerModule"; 54 | } 55 | 56 | return string.Empty; 57 | } 58 | 59 | internal static string GetCreateTableQuery(DatabaseType databaseType) 60 | { 61 | switch (databaseType) 62 | { 63 | case DatabaseType.MsSql: 64 | return @"create table [{0}] 65 | ( 66 | [Id] int not null primary key identity, 67 | [Text] nvarchar(4000) null, 68 | [DateTime] datetime null, 69 | [Log_Level] nvarchar(10) null, 70 | [CallingClass] nvarchar(500) NULL, 71 | [CallingMethod] nvarchar(500) NULL 72 | );"; 73 | case DatabaseType.Oracle: 74 | return @"create table {0} 75 | ( 76 | Id int not null primary key, 77 | Text varchar2(4000) null, 78 | DateTime date null, 79 | Log_Level varchar2(10) null, 80 | CallingClass varchar2(500) NULL, 81 | CallingMethod varchar2(500) NULL 82 | ); 83 | create sequence seq_log nocache;"; 84 | case DatabaseType.MySql: 85 | return @"create table {0} 86 | ( 87 | Id int not null auto_increment, 88 | Text varchar(4000) null, 89 | DateTime datetime null, 90 | Log_Level varchar(10) null, 91 | CallingClass varchar(500) NULL, 92 | CallingMethod varchar(500) NULL, 93 | PRIMARY KEY (Id) 94 | );"; 95 | } 96 | 97 | return string.Empty; 98 | } 99 | 100 | internal static string GetCheckIfShouldCreateTableQuery(DatabaseType databaseType) 101 | { 102 | switch (databaseType) 103 | { 104 | case DatabaseType.MsSql: 105 | return @"SELECT object_name(object_id) as table_name 106 | FROM sys.objects 107 | WHERE type_desc LIKE '%USER_TABLE' 108 | AND lower(object_name(object_id)) like @tableName;"; 109 | case DatabaseType.Oracle: 110 | return @"SELECT TABLE_NAME 111 | FROM ALL_TABLES 112 | WHERE LOWER(TABLE_NAME) LIKE :tableName"; 113 | case DatabaseType.MySql: 114 | return @"SELECT table_name 115 | FROM information_schema.tables 116 | WHERE LOWER(table_name) = @tableName;"; 117 | } 118 | 119 | return string.Empty; 120 | } 121 | 122 | internal static string GetInsertCommand(DatabaseType databaseType, string tableName) 123 | { 124 | switch (databaseType) 125 | { 126 | case DatabaseType.MsSql: 127 | return string.Format(@"insert into {0} ([Text], [DateTime], [Log_Level], [CallingClass], [CallingMethod]) 128 | values (@text, @dateTime, @log_level, @callingClass, @callingMethod);", tableName); 129 | case DatabaseType.Oracle: 130 | return string.Format(@"insert into {0} (Id, Text, DateTime, Log_Level, CallingClass, CallingMethod) 131 | values (seq_log.nextval, :text, :dateTime, :log_level, :callingClass, :callingMethod)", tableName); 132 | case DatabaseType.MySql: 133 | return string.Format(@"insert into {0} (Text, DateTime, Log_Level, CallingClass, CallingMethod) 134 | values (@text, @dateTime, @log_level, @callingClass, @callingMethod);", tableName); 135 | } 136 | 137 | return string.Empty; 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /SimpleLogger/Logger.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Reflection; 6 | using SimpleLogger.Logging; 7 | using SimpleLogger.Logging.Handlers; 8 | using SimpleLogger.Logging.Module; 9 | 10 | namespace SimpleLogger 11 | { 12 | public static class Logger 13 | { 14 | private static readonly LogPublisher LogPublisher; 15 | private static readonly ModuleManager ModuleManager; 16 | private static readonly DebugLogger DebugLogger; 17 | 18 | private static readonly object Sync = new object(); 19 | private static Level _defaultLevel = Level.Info; 20 | private static bool _isTurned = true; 21 | private static bool _isTurnedDebug = true; 22 | 23 | public enum Level 24 | { 25 | None, 26 | Debug, 27 | Fine, 28 | Info, 29 | Warning, 30 | Error, 31 | Severe 32 | } 33 | 34 | static Logger() 35 | { 36 | lock (Sync) 37 | { 38 | LogPublisher = new LogPublisher(); 39 | ModuleManager = new ModuleManager(); 40 | DebugLogger = new DebugLogger(); 41 | } 42 | } 43 | 44 | public static void DefaultInitialization() 45 | { 46 | LoggerHandlerManager 47 | .AddHandler(new ConsoleLoggerHandler()) 48 | .AddHandler(new FileLoggerHandler()); 49 | 50 | Log(Level.Info, "Default initialization"); 51 | } 52 | 53 | public static Level DefaultLevel 54 | { 55 | get { return _defaultLevel; } 56 | set { _defaultLevel = value; } 57 | } 58 | 59 | public static ILoggerHandlerManager LoggerHandlerManager 60 | { 61 | get { return LogPublisher; } 62 | } 63 | 64 | public static void Log() 65 | { 66 | Log("There is no message"); 67 | } 68 | 69 | public static void Log(string message) 70 | { 71 | Log(_defaultLevel, message); 72 | } 73 | 74 | public static void Log(Level level, string message) 75 | { 76 | var stackFrame = FindStackFrame(); 77 | var methodBase = GetCallingMethodBase(stackFrame); 78 | var callingMethod = methodBase.Name; 79 | var callingClass = methodBase.ReflectedType.Name; 80 | var lineNumber = stackFrame.GetFileLineNumber(); 81 | 82 | Log(level, message, callingClass, callingMethod, lineNumber); 83 | } 84 | 85 | public static void Log(Exception exception) 86 | { 87 | Log(Level.Error, exception.Message); 88 | ModuleManager.ExceptionLog(exception); 89 | } 90 | 91 | public static void Log(Exception exception) where TClass : class 92 | { 93 | var message = string.Format("Log exception -> Message: {0}\nStackTrace: {1}", exception.Message, 94 | exception.StackTrace); 95 | Log(Level.Error, message); 96 | } 97 | 98 | public static void Log(string message) where TClass : class 99 | { 100 | Log(_defaultLevel, message); 101 | } 102 | 103 | public static void Log(Level level, string message) where TClass : class 104 | { 105 | var stackFrame = FindStackFrame(); 106 | var methodBase = GetCallingMethodBase(stackFrame); 107 | var callingMethod = methodBase.Name; 108 | var callingClass = typeof(TClass).Name; 109 | var lineNumber = stackFrame.GetFileLineNumber(); 110 | 111 | Log(level, message, callingClass, callingMethod, lineNumber); 112 | } 113 | 114 | private static void Log(Level level, string message, string callingClass, string callingMethod, int lineNumber) 115 | { 116 | if (!_isTurned || (!_isTurnedDebug && level == Level.Debug)) 117 | return; 118 | 119 | var currentDateTime = DateTime.Now; 120 | 121 | ModuleManager.BeforeLog(); 122 | var logMessage = new LogMessage(level, message, currentDateTime, callingClass, callingMethod, lineNumber); 123 | LogPublisher.Publish(logMessage); 124 | ModuleManager.AfterLog(logMessage); 125 | } 126 | 127 | private static MethodBase GetCallingMethodBase(StackFrame stackFrame) 128 | { 129 | return stackFrame == null 130 | ? MethodBase.GetCurrentMethod() : stackFrame.GetMethod(); 131 | } 132 | 133 | private static StackFrame FindStackFrame() 134 | { 135 | var stackTrace = new StackTrace(); 136 | for (var i = 0; i < stackTrace.GetFrames().Count(); i++) 137 | { 138 | var methodBase = stackTrace.GetFrame(i).GetMethod(); 139 | var name = MethodBase.GetCurrentMethod().Name; 140 | if (!methodBase.Name.Equals("Log") && !methodBase.Name.Equals(name)) 141 | return new StackFrame(i, true); 142 | } 143 | return null; 144 | } 145 | 146 | public static void On() 147 | { 148 | _isTurned = true; 149 | } 150 | 151 | public static void Off() 152 | { 153 | _isTurned = false; 154 | } 155 | 156 | public static void DebugOn() 157 | { 158 | _isTurnedDebug = true; 159 | } 160 | 161 | public static void DebugOff() 162 | { 163 | _isTurnedDebug = false; 164 | } 165 | 166 | public static IEnumerable Messages 167 | { 168 | get { return LogPublisher.Messages; } 169 | } 170 | 171 | public static DebugLogger Debug 172 | { 173 | get { return DebugLogger; } 174 | } 175 | 176 | public static ModuleManager Modules 177 | { 178 | get { return ModuleManager; } 179 | } 180 | 181 | public static bool StoreLogMessages 182 | { 183 | get { return LogPublisher.StoreLogMessages; } 184 | set { LogPublisher.StoreLogMessages = value; } 185 | } 186 | 187 | static class FilterPredicates 188 | { 189 | public static bool ByLevelHigher(Level logMessLevel, Level filterLevel) 190 | { 191 | return ((int)logMessLevel >= (int)filterLevel); 192 | } 193 | 194 | public static bool ByLevelLower(Level logMessLevel, Level filterLevel) 195 | { 196 | return ((int)logMessLevel <= (int)filterLevel); 197 | } 198 | 199 | public static bool ByLevelExactly(Level logMessLevel, Level filterLevel) 200 | { 201 | return ((int)logMessLevel == (int)filterLevel); 202 | } 203 | 204 | public static bool ByLevel(LogMessage logMessage, Level filterLevel, Func filterPred) 205 | { 206 | return filterPred(logMessage.Level, filterLevel); 207 | } 208 | } 209 | 210 | public class FilterByLevel 211 | { 212 | public Level FilteredLevel { get; set; } 213 | public bool ExactlyLevel { get; set; } 214 | public bool OnlyHigherLevel { get; set; } 215 | 216 | public FilterByLevel(Level level) 217 | { 218 | FilteredLevel = level; 219 | ExactlyLevel = true; 220 | OnlyHigherLevel = true; 221 | } 222 | 223 | public FilterByLevel() 224 | { 225 | ExactlyLevel = false; 226 | OnlyHigherLevel = true; 227 | } 228 | 229 | public Predicate Filter { get { return delegate(LogMessage logMessage) { 230 | return FilterPredicates.ByLevel(logMessage, FilteredLevel, delegate(Level lm, Level fl) { 231 | return ExactlyLevel ? 232 | FilterPredicates.ByLevelExactly(lm, fl) : 233 | (OnlyHigherLevel ? 234 | FilterPredicates.ByLevelHigher(lm, fl) : 235 | FilterPredicates.ByLevelLower(lm, fl) 236 | ); 237 | }); 238 | }; 239 | } } 240 | } 241 | } 242 | } 243 | --------------------------------------------------------------------------------