一个简单的写入日志类

工作中经常要用到将信息写入文本,网上也有很多出名的工具包,如:log4net,也有很多大神写了各种库,但每次都要各种配置,或者就是有些功能不需要,觉得用的不是很爽,本身需求只是简单的记录而已,所以写了个简单的写入类,功能比较单一,适合初学者

public class Logger
    {
        private static string logdir = System.AppDomain.CurrentDomain.BaseDirectory + "/log/";
        private static string logfilename = logdir + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
        private static Logger logger = null;
        private static object _lock = new object();

        private Logger() { }
        public static Logger GetLogger()
        {
            if (logger == null)
            {
                if (!Directory.Exists(logdir))
                    Directory.CreateDirectory(logdir);
                logger = new Logger();
            }
            return logger;
        }

        public static int i = 0;
        public void WriteLog(string content)
        {
            Task.Factory.StartNew(() =>
            {
                lock (_lock)
                {
                    FileStream _filestream;
                    if (!File.Exists(logfilename))
                        _filestream = new FileStream(logfilename, System.IO.FileMode.Create);
                    else
                        _filestream = new FileStream(Logger.logfilename, FileMode.Append, FileAccess.Write);

                    using (_filestream)
                    {
                        using (var sw = new StreamWriter(_filestream, Encoding.Default))
                        {
                            sw.WriteLine("[{0}]:{1}_{2}", DateTime.Now.ToString(), content, i++);
                        }
                    }
                    //System.Threading.Thread.Sleep(1000*4);
                }
            });

        }
    }

  调用测试:

class Program
    {
        static void Main(string[] args)
        {

            for (var i = 0; i < 99999999; i++)
            {
                var _task = System.Threading.Tasks.Task.Factory.StartNew(() =>
                {
                    var _content = DateTime.Now.ToString();
                    WLX.SimpleLogger.Logger.GetLogger().WriteLog(_content);
                });
            }

            Console.ReadKey();

        }
    }

  

posted @ 2016-09-21 10:44  王立新  阅读(218)  评论(0编辑  收藏  举报