公布一个简单的日志记录方法

 

 没有复杂的算法,也没有打算用log4net之类的东东。只要这个,就可以在目录的文件中,看到日志信息

一句话:简单实用。

 

 

 public static void Log(string message)
        {
            if (message != "")
            {
                Random randObj = new Random(DateTime.Now.Millisecond);
                int file = randObj.Next() + 1;
                string filename = DateTime.Now.ToString("yyyyMMdd") + ".txt";
                try
                {
                    FileInfo fi = new FileInfo(HttpContext.Current.Server.MapPath("~//Log//" + filename));
                    if (!fi.Exists)
                    {
                        using (StreamWriter sw = fi.CreateText())
                        {
                            sw.WriteLine(DateTime.Now + "   \n" + message + System.Environment.NewLine);
                            sw.Close();
                        }
                    }
                    else
                    {
                        using (StreamWriter sw = fi.AppendText())
                        {
                            sw.WriteLine(DateTime.Now + "   \n" + message + System.Environment.NewLine);
                            sw.Close();
                        }
                    }
                }
                catch
                {
                }
            }
        }

把 HttpContext.Current.Server 用System.AppDomain.Current 可以用在CS应用程序中。

 

posted @ 2008-10-23 18:25  信息化建设  阅读(628)  评论(0编辑  收藏  举报