Click here to Skip to main content
15,868,016 members
Articles / Programming Languages / C#
Tip/Trick

Logging.Net

Rate me:
Please Sign up or sign in to vote.
3.75/5 (3 votes)
24 Jul 2013CPOL 9.3K   236   7  
Simple logging library. You can format your text, write it on console, and store it in a file or database.

Introduction

I created this simple library that you can use to format your text, write it on console and store it in a file or database.

Screenshots

Image 1

Image 2

Image 3

Log Level

  • Trace - Very detailed log messages
  • Debug - Detailed log messages
  • Information - Informational messages
  • Warning - Warning messages
  • Error - Error messages
  • Fatal - Fatal error messages
  • Success - Success messages

Format Patterns

  • %hh - Current hour
  • %mm - Current minute
  • %ss - Current second
  • %MM - Current month
  • %dd - Current day
  • %yy - Current year
  • %class - Class name where WriteLine has been called
  • %method - Method name where WriteLine has been called
  • %text - Line text
  • %loglevel - Log level name
  • %username - Current windows user name
  • %timestamp - Current timestamp
  • %{ConsoleColorName} - Set color for multicolor line

The Library

C#
/// <summary>
/// Format and write the line
/// </summary>
/// <param name="Text">Text to write</param>     
/// <param name="LogLevel">Log level</param>
public void WriteLine(string Text, LogLevel LogLevel)
{
  //Skip line if MinimumLogLevel is higher than the given LogLevel 
  if (LogLevel >= MinimumLogLevel)
  {               
    //Temp variable of the log format
    string FinalString = Format;
    //Set the given LogLevel console color
    Console.ForegroundColor = 
      GetLogLevelInfoByLogLevel(LogLevel).LogLevelColor;
  
    //Replace all values
    FinalString = ReplaceValues(FinalString, Text, LogLevel);
  
    //Set ConsoleColor by color parameters
    while (FinalString.IndexOf("%{") > 0)
    {
      int startIndex = FinalString.IndexOf("%{");
      int endIndex = FinalString.IndexOf("}");
      Console.Write(FinalString.Substring(0, startIndex));
      if (LogFileStream != null)
      {
        LogFileStream.Write(FinalString.Substring(0, startIndex));
      }
      string ColorName = FinalString.Substring(startIndex + 2, 
                              endIndex - (startIndex + 2));
      ConsoleColor ConsoleColor;
      if (Enum.TryParse(ColorName, true, out ConsoleColor))
      {
        Console.ForegroundColor = ConsoleColor;
      }
      FinalString = FinalString.Substring(endIndex + 1);
    }

    Console.WriteLine(FinalString);
    if (LogFileStream != null)
    {
      //Write Log to file
      LogFileStream.WriteLine(FinalString);
      LogFileStream.Flush();
    }
    if (DatabaseManager != null)
    {
      //Write Log to database
      string FinalQuery = LogQueryFormat;
      FinalQuery = ReplaceValues(FinalQuery, Text, LogLevel);
      DatabaseManager.GetClient().ExecuteQuery(FinalQuery);
    }
  }
}

private string ReplaceValues(string String, string Text, LogLevel LogLevel)
{            
  StackFrame _SF = new StackTrace().GetFrame(2);
  //Current Hour
  String = String.Replace("%hh", DateTime.Now.ToString("hh"));
  //Minute            
  String = String.Replace("%mm", DateTime.Now.ToString("mm"));
  //Second
  String = String.Replace("%ss", DateTime.Now.ToString("ss"));
  //Month
  String = String.Replace("%MM", DateTime.Now.ToString("MM"));
  //Day
  String = String.Replace("%dd", DateTime.Now.ToString("dd"));
  //Year
  String = String.Replace("%yy", DateTime.Now.ToString("yy"));
  //Class name where WriteLine has been called
  String = String.Replace("%class", _SF.GetMethod().ReflectedType.Name);
  //method name where WriteLine has been called
  String = String.Replace("%method", _SF.GetMethod().Name);
  //Text
  String = String.Replace("%text", Text);
  //LogLevel name
  String = String.Replace("%loglevel", LogLevel.ToString());
  //User login name
  String = String.Replace("%username", Environment.UserName);
  //Current timestamp
  String = String.Replace("%timestamp", Stopwatch.GetTimestamp().ToString());
  return String;
} 

Test Program and How to Use the Library

Example of a Format String

[%loglevel][%dd/%MM/%yy][%hh:%mm:%ss]%{cyan}[%class.%method] > %{red}%text 

Code

C#
static void Main(string[] args)
{
  //Create a new logging with our custom format
  Logging MyLog = new Logging(
    "[%loglevel][%dd/%MM/%yy][%hh:%mm:%ss]%{cyan}[%class.%method] > %{red}%text");
  //the MinimumLogLevel to display the line
  MyLog.MinimumLogLevel = LogLevel.Debug;
  //Name of a file where logs will be stored
  MyLog.SetLogFile("mylog.txt");
  //Mysql Query Format
  string QueryFormat = "insert into mylog values ('%loglevel','%class','%method','%text')";
  //Mysql Connection parameters
  MyLog.SetLogDatabase("127.0.0.1", 3306, 
    "root", "123456", "test", QueryFormat);
  //Write some logs
  MyLog.WriteLine("log", LogLevel.Debug);
  MyLog.WriteLine("information", LogLevel.Information);
  MyLog.WriteLine("warning", LogLevel.Warning);
  MyLog.WriteLine("error", LogLevel.Error);
  MyLog.WriteLine("fatal", LogLevel.Fatal);
  //Change Success LogLevel Default Color
  MyLog.ChangeLogLevelColor(LogLevel.Success, ConsoleColor.DarkGreen); 
  MyLog.WriteLine("success", LogLevel.Success);

  //Create a exception log
  Logging ExceptionLog = new Logging("[%dd/%MM/%yy][%hh:%mm:%ss][%class.%method] > %text");
  ExceptionLog.MinimumLogLevel = LogLevel.Error;
  ExceptionLog.SetLogFile("exceptionlog.txt");
  string QueryFormat2 = 
    "insert into exception_log values ('%timestamp','%class','%method','%text')";
  ExceptionLog.SetLogDatabase("127.0.0.1", 3306, "root", 
                              "123456", "test", QueryFormat2);
  ExceptionLog.WriteLine("Exception: ...", LogLevel.Error);         
   
  Console.ReadLine();
} 

How to Import the Library

  • Add reference to Logging.Net.dll and MySql.Data.dll
  • Add:
  • C#
    using LoggingNet; 
  • Done

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Student
Italy Italy

Comments and Discussions

 
-- There are no messages in this forum --