LanceZhang’s Blog

Dear friends, Welcome to my blog.

A common Log class for .NET

LanceZhang.Common.Log

Methods: 

1. Output(string)

This method is used for record the normal Logs, it will create a file name like “log_20090408.txt” to the root directory of your application, and append the log message:

 

2.OutputError(string)

Just like the Output method, this method not only output the log message, but also output the following messages:

  • File name
  • Method name
  • Line number
  • Column number

which is useful for an exception analysis

Example:

    try
    {
        
int i = 8;
        
int j = 0;
        
int c = i / j;
    }
    
catch (Exception ex)
    {
        Log.OutputError(ex.Message);
    }

Then, the output is like:

 

Code: 

/**//****************************** Module Header ******************************
* Module Name:    Log.cs
* Project:    LanceZhang.Common
* Copyright (c) Lance Zhang (blodfox777@hotmail.com)

* History:
* * 3/7/2009 2:50 Lance Zhang Created
**************************************************************************
*/


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace LanceZhang.Common
{
    
public static class Log
    
{
        
private static object lockobj=new object();

        
private static void WriteToFile(string filename, string content)
        
{
            
using (StreamWriter sw = new StreamWriter(filename, true))
            
{
                sw.WriteLine(content);
                sw.Close();
            }

        }


        
private static string GetDateTime()
        
{
            
return [ + DateTime.Now.ToString(HH:mm:ss+ ;
        }


        
public static void Output(string msg)
        
{
            
lock (lockobj)
            
{
                Log.WriteToFile(Directory.GetCurrentDirectory()
+ @”\log_ + DateTime.Now.ToString(yyyyMMdd+ .txt, GetDateTime() + msg);
            }

        }


        
public static void OutputError(string msg)
        
{
            
lock (lockobj)
            
{
                StackFrame sf 
= new StackTrace(true).GetFrame(1);
                StringBuilder sb 
= new StringBuilder(GetDateTime());
                sb.Append(
ERROR:);
                sb.AppendLine(msg);
                sb.AppendLine(
Error from:);
                sb.AppendLine(sf.GetFileName());
                sb.Append(
Line:);
                sb.AppendLine(sf.GetFileLineNumber().ToString());
                sb.Append(
Column:);
                sb.AppendLine(sf.GetFileColumnNumber().ToString());
                sb.Append(
Method:);
                sb.Append(sf.GetMethod().Name);
                Log.WriteToFile(Directory.GetCurrentDirectory() 
+ @”\log_ + DateTime.Now.ToString(yyyyMMdd+ .txt,  sb.ToString());
            }

        }

    }

}

April 8, 2009 Posted by | Code and Solution, Develop Resource | | 3 Comments