Logger class : Log « Development Class « C# / C Sharp






Logger class

      
/****************************************************************************************************************
*                                                                                                               *
* Copyright (C) 2011 5173.com                                                                                   *
* This project may be copied only under the terms of the Apache License 2.0.                                    *
* Please visit the project Home Page http://bqqapicsharp.codeplex.com/ for more detail.                         *
*                                                                                                               *
****************************************************************************************************************/

namespace BQQAPIClient.Core.Utility
{
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Reflection;
    using System.Text;
    using System.Threading;

    public enum LogLevel
    {
        None = 0,
        Debug = 1,
        Info = 2,
        Warning = 3,
        Error = 4,
    }

    internal class Logger
    {
        private static object locker = new object();
        private static StreamWriter sw;
        private static LogLevel logLevel;
        private static Timer changePathTimer;
        private static readonly int CHANGEPATHINTERVAL = 60 * 1000;
        private static readonly string LOGFILENAMEFORMAT = "yyyyMMddHH";
        private static readonly string LOGLINEFORMAT = "HH:mm:ss_ffff";

        static Logger()
        {
            changePathTimer = new Timer(state =>
            {
                sw.Close();
                InitStreamWriter();
            }, null, CHANGEPATHINTERVAL, CHANGEPATHINTERVAL);
            InitStreamWriter();
        }

        public static void Dispose()
        {
            lock (locker)
            {
                changePathTimer.Dispose();
                sw.Flush();
                sw.Close();
            }
        }

        public static void SetLogLevel(LogLevel level)
        {
            logLevel = level;
        }

        private static void InitStreamWriter()
        {
            sw = new StreamWriter(GetLogFileName(), true, Encoding.UTF8, 1024);
            sw.AutoFlush = true;
        }

        private static string GetLogFileName()
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log");
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
            string file = DateTime.Now.ToString(LOGFILENAMEFORMAT) + ".txt";
            return Path.Combine(path, file);
        }

        public static void Debug(string s)
        {
            if ((int)logLevel <= (int)LogLevel.Debug)
                Log(LogLevel.Debug, s);
        }

        public static void Debug(string format, params object[] args)
        {
            if ((int)logLevel <= (int)LogLevel.Debug)
                Log(LogLevel.Debug, format, args);
        }

        public static void Info(string s)
        {
            if ((int)logLevel <= (int)LogLevel.Info)
                Log(LogLevel.Info, s);
        }

        public static void Info(string format, params object[] args)
        {
            if ((int)logLevel <= (int)LogLevel.Info)
                Log(LogLevel.Info, format, args);
        }

        public static void Warning(string s)
        {
            if ((int)logLevel <= (int)LogLevel.Debug)
                Log(LogLevel.Warning, s);
        }

        public static void Warning(string format, params object[] args)
        {
            if ((int)logLevel <= (int)LogLevel.Debug)
                Log(LogLevel.Warning, format, args);
        }

        public static void Error(string s)
        {
            if ((int)logLevel <= (int)LogLevel.Error)
                Log(LogLevel.Error, s);
        }

        public static void Error(string format, params object[] args)
        {
            if ((int)logLevel <= (int)LogLevel.Error)
                Log(LogLevel.Error, format, args);
        }

        private static void Log(LogLevel logLevel, string s)
        {
            lock (locker)
            {
                sw.WriteLine(WrapWithContext(logLevel, s));
            }
        }

        private static void Log(LogLevel logLevel, string format, params object[] args)
        {
            Log(logLevel, string.Format(format, args));
        }

        private static string WrapWithContext(LogLevel logLevel, string s)
        {
            StackTrace strackTrace = new StackTrace();
            StackFrame[] stackFrames = strackTrace.GetFrames();
            StackFrame stackFrame = null;
            for (int i = 0; i < stackFrames.Length; i++)
            {
                if (stackFrames[i].GetMethod().ReflectedType != typeof(Logger))
                {
                    stackFrame = stackFrames[i];
                    break;
                }
            }

            MethodBase methodBase = stackFrame.GetMethod();
            string method = string.Format("{0}.{1}", methodBase.DeclaringType.Name, methodBase.Name);

            return string.Format("[{0}] @{3} #{4} {1} - {2}", logLevel, method, s, DateTime.Now.ToString(LOGLINEFORMAT), Thread.CurrentThread.ManagedThreadId);
        }
    }
}

   
    
    
    
    
    
  








Related examples in the same category

1.Demonstrates registering and event source and writing to the Application LogDemonstrates registering and event source and writing to the Application Log
2.Add a EventLogTraceListener to the listener collection and writing error messages to the Application log
3.Test Log
4.Set Text Output To Event LogSet Text Output To Event Log
5.Log utility based on File with File.AppendAllText
6.Log message with StreamWriter
7.File Logger
8.Log error to a file
9.Logger
10.Log Utility
11.Log Exception with Event Log
12.Logger 2
13.Instantiates a Trace log for detailed tracking of an application's internal activities.
14.Your own Logger
15.Implements a TextWriter for writing information to the debugger log.